package com.ymttest.business.service;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.ClientProtocolException;
import org.joda.time.DateTime;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.common.collect.Lists;
import com.ymatou.iapi.delivery.parameter.DeliverGoodsReq;
import com.ymatou.iapi.delivery.parameter.DeliveryInfo;
import com.ymatou.iapi.delivery.parameter.ModifyOrSupplementBillNoInfo;
import com.ymatou.iapi.delivery.parameter.ModifyOrSupplementBillNoReq;
import com.ymatou.iapi.delivery.service.DeliverGoodsCall;
import com.ymatou.iapi.delivery.service.ModifyOrSupplementBillNoCall;
import com.ymatou.iapi.leaf.parameter.GetSeqReq;
import com.ymatou.iapi.leaf.service.GetSeqIdsCall;
import com.ymatou.iapi.optrade.parameter.enums.AppTerminalSourceEnum;
import com.ymatou.iapi.optrade.parameter.enums.AuthenticateFeeTypeEnum;
import com.ymatou.iapi.optrade.parameter.enums.AuthenticateFreightTypeEnum;
import com.ymatou.iapi.optrade.parameter.enums.BondedAreaEnum;
import com.ymatou.iapi.optrade.parameter.enums.CancelOrderTypeEnum;
import com.ymatou.iapi.optrade.parameter.enums.CouponApplianceTypeEnum;
import com.ymatou.iapi.optrade.parameter.enums.LogisticsTypeEnum;
import com.ymatou.iapi.optrade.parameter.enums.OrderSourceEnum;
import com.ymatou.iapi.optrade.parameter.enums.ProductRefundChannelEnum;
import com.ymatou.iapi.optrade.parameter.enums.PromotionTypeEnum;
import com.ymatou.iapi.optrade.parameter.enums.SalesTypeEnum;
import com.ymatou.iapi.optrade.parameter.enums.TerminalSourceEnum;
import com.ymatou.iapi.optrade.parameter.req.AcceptOrderReq;
import com.ymatou.iapi.optrade.parameter.req.AuthenticateCenterNotifyReq;
import com.ymatou.iapi.optrade.parameter.req.AuthenticateDeliveryReq;
import com.ymatou.iapi.optrade.parameter.req.CancelOrderReq;
import com.ymatou.iapi.optrade.parameter.req.ConfirmReceiveReq;
import com.ymatou.iapi.optrade.parameter.req.MarkOrderLockReq;
import com.ymatou.iapi.optrade.parameter.req.PayReq;
import com.ymatou.iapi.optrade.parameter.req.PlaceOrderReq;
import com.ymatou.iapi.optrade.parameter.req.SyncSignedOrderReq;
import com.ymatou.iapi.optrade.parameter.utill.Utils;
import com.ymatou.iapi.optrade.parameter.vo.ActivityVo;
import com.ymatou.iapi.optrade.parameter.vo.BizVo;
import com.ymatou.iapi.optrade.parameter.vo.CatalogApportionVo;
import com.ymatou.iapi.optrade.parameter.vo.CouponVo;
import com.ymatou.iapi.optrade.parameter.vo.IdentifyProdArrivedVo;
import com.ymatou.iapi.optrade.parameter.vo.OrderGroupVo;
import com.ymatou.iapi.optrade.parameter.vo.OrderItemVo;
import com.ymatou.iapi.optrade.parameter.vo.OrderVo;
import com.ymatou.iapi.optrade.parameter.vo.PrepaidCardVo;
import com.ymatou.iapi.optrade.parameter.vo.SellerPromotionVo;
import com.ymatou.iapi.optrade.parameter.vo.SyncSignedOrderBizParamVo;
import com.ymatou.iapi.optrade.parameter.vo.ThirdPartyPromotionVo;
import com.ymatou.iapi.optrade.parameter.vo.UbuyUserVo;
import com.ymatou.iapi.optrade.resp.Order;
import com.ymatou.iapi.optrade.resp.TradingServiceResp;
import com.ymatou.iapi.optrade.service.AuthenticateCenterNotifyCall;
import com.ymatou.iapi.optrade.service.AuthenticateDeliveryCall;
import com.ymatou.iapi.optrade.service.CancelOrderCall;
import com.ymatou.iapi.optrade.service.ConfirmReceiveCall;
import com.ymatou.iapi.optrade.service.MarkOrderLockCall;
import com.ymatou.iapi.optrade.service.PayReqCall;
import com.ymatou.iapi.optrade.service.PlaceOrderCall;
import com.ymatou.iapi.optrade.service.PrepaidCardService;
import com.ymatou.iapi.optrade.service.RefundService;
import com.ymatou.iapi.optrade.service.SellerAcceptOrderCall;
import com.ymatou.iapi.optrade.service.SyncSignedOrderCall;
import com.ymatou.iapi.payment.parameter.QueryByTradingIdBean;
import com.ymatou.iapi.payment.service.QueryByTradingIdCall;
import com.ymatou.iapi.proditem.service.GetProductInfoByProductIdCall;
import com.ymatou.iapi.productmanager.parameter.UpdateProductCatalogDto;
import com.ymatou.iapi.productmanager.parameter.UpdateProductCatalogsBean;
import com.ymatou.iapi.productmanager.parameter.product.AddSellerProductRequest;
import com.ymatou.iapi.productmanager.service.UpdateProductCatalogsCall;
import com.ymatou.iapi.synctrade.service.TradingSyncService;
import com.ymt.base.YmatouEasyCall;
import com.ymt.core.tool.Logger;
import com.ymttest.database.model.YmtCatalogsI;
import com.ymttest.database.sharding.db.sharding.model.OrderDetailPo;
import com.ymttest.database.sharding.db.sharding.model.OrderPo;
import com.ymttest.database.sharding.db.sqlwapper.OrderShardingWapper;
import com.ymttest.database.sqlwapper.YmtCatalogsIWapper;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.TestDataManager;

public class TradingCallService {

	// 是否为新优惠券服务
	public static final boolean IS_NEW_COUPON_SERVER = true;

	// 新商品服务为 java 服务
	public static final boolean IS_NEW_PRO_SERVER = true;

	public static class ProductVo {

		public ProductVo(String productId, String catalogId) {

			this.productId = productId;
			this.catalogId = catalogId;

		}

		String productId;
		String catalogId;

		int stock;
		int activityStock;

		long activity;
		long productInActivityId;

		public String getProductId() {
			return productId;
		}

		public void setProductId(String productId) {
			this.productId = productId;
		}

		public String getCatalogId() {
			return catalogId;
		}

		public void setCatalogId(String catalogId) {
			this.catalogId = catalogId;
		}

		public int getStock() {
			return stock;
		}

		public void setStock(int stock) {
			this.stock = stock;
		}

		public int getActivityStock() {
			return activityStock;
		}

		public void setActivityStock(int activityStock) {
			this.activityStock = activityStock;
		}

		public long getActivity() {
			return activity;
		}

		public void setActivity(long activity) {
			this.activity = activity;
		}

		public long getProductInActivityId() {
			return productInActivityId;
		}

		public void setProductInActivityId(long productInActivityId) {
			this.productInActivityId = productInActivityId;
		}
	}

	/**
	 * buildStandPlaceOrderReq 一个商家，一个商品，生成一个订单
	 * 
	 * @param isBargainGroup
	 *            是否砍价团订单 砍价团订单不由交易扣库存
	 * @return
	 */
	public static PlaceOrderReq buildStandPlaceOrderReq(boolean isBargainGroup) {
		return buildStandPlaceOrderReq(isBargainGroup, false);
	}

	/**
	 * buildStandPlaceOrderReq 一个商家，一个商品，生成一个订单
	 * 
	 * @param isBargainGroup
	 *            是否砍价团订单 砍价团订单不由交易扣库存
	 * @param canPayDeduct
	 *            是否使用平台立减支付金额
	 * @return
	 */
	public static PlaceOrderReq buildStandPlaceOrderReq(boolean isBargainGroup,
			boolean canPayDeduct) {

		return buildStandPlaceOrderReq(isBargainGroup, canPayDeduct,
				Long.valueOf(EnvSetup.getData("BuyUserId")),
//				Long.valueOf(EnvSetup.getData("autotest_seller1")),
				Long.valueOf(24635724),
				String.valueOf(EnvSetup.getData("autotest_sellerName1")));
	}

	/**
	 * buildStandPlaceOrderReq 一个商家，一个商品，生成一个订单
	 * 
	 * @param isBargainGroup
	 *            是否砍价团订单 砍价团订单不由交易扣库存
	 * @param canPayDeduct
	 *            是否使用平台立减支付金额
	 * @return
	 */
	public static PlaceOrderReq buildStandPlaceOrderReq(boolean isBargainGroup,
			long sellerId, String sellerName) {

		return buildStandPlaceOrderReq(isBargainGroup, false,
				Long.valueOf(EnvSetup.getData("BuyUserId")), sellerId,
				sellerName);
	}

	/**
	 * buildStandPlaceOrderReq 一个商家，一个商品，生成一个订单
	 * 
	 * @param isBargainGroup
	 *            是否砍价团订单 砍价团订单不由交易扣库存
	 * @param canPayDeduct
	 *            是否使用平台立减支付金额
	 * @userId userId 买家id
	 * @return
	 */
	public static PlaceOrderReq buildStandPlaceOrderReq(boolean isBargainGroup,
			boolean canPayDeduct, long userId) {

		return buildStandPlaceOrderReq(isBargainGroup, canPayDeduct, userId,
				Long.valueOf(EnvSetup.getData("autotest_seller1")),
				String.valueOf(EnvSetup.getData("autotest_sellerName1")));
	}

	/**
	 * buildStandPlaceOrderReq 一个商家，一个商品，生成一个订单
	 * 
	 * @param isBargainGroup
	 *            是否砍价团订单 砍价团订单不由交易扣库存
	 * @param canPayDeduct
	 *            是否使用平台立减支付金额
	 * @userId userId 买家id
	 * @sellerId sellerId 买手id
	 * @sellerId sellerName 买手名称
	 * @return
	 */
	public static PlaceOrderReq buildStandPlaceOrderReq(boolean isBargainGroup,
			boolean canPayDeduct, long userId, long sellerId, String sellerName) {

		PlaceOrderReq req = new PlaceOrderReq();
		
		req.setAddressId(772208L);
		req.setRecvMobile("136" + TestDataManager.getRandomNum(8));
		req.setRecvName("testUser");
		req.setAppId("ymt autotest");
//		req.setUserId(20325087);
		req.setUserId(userId);

		req.setAddress("上海 静安 江场三路");
		req.setPostCode("200000");

		req.setEquipmentId(TestDataManager.getRandomUUID().toString());
		req.setDeviceId(TestDataManager.getRandomUUID().toString());
		req.setSourceIp(TestDataManager.getRandomIp());

		req.setAppTerminalSource(AppTerminalSourceEnum.Phone);
		req.setOrderSource(OrderSourceEnum.Wechat);
		req.setTerminalSource(TerminalSourceEnum.Android);

		req.setMainOrderId(genMainOrderId(req.getUserId()));

		if (canPayDeduct) {
			req.setPayDeductAmount(new BigDecimal(new Random().nextInt(10))
					.add(BigDecimal.ONE).setScale(2));
		}

		OrderVo orderVo;

		if (isBargainGroup) {

			// 设置为砍价团订单,不需要交易扣库存
			BizVo biz = new BizVo();

			biz.setBizId(TestDataManager.getRandomNum(9));
			biz.setBizSubType(1);
			biz.setBizType(1);

			req.setBizSource(biz);

			orderVo = createOrderVo(TestDataManager.getRandomUUID().toString());
		}

		else {

//////			// 创建一个普通商品
			TradingCallService.ProductVo pro = TradingCallService.creaderPro(
					sellerId, sellerName, 100);
			
//			// 创建一个普通商品
//			TradingCallService.ProductVo pro = TradingCallService.creaderPro(
//					3383L, "zhangyi_seller0002", 100);

			orderVo = createOrderVo(Lists.newArrayList(pro));
			orderVo.setLogisticsType(LogisticsTypeEnum.OVERSEAS_DELIVERY);
			orderVo.setLogisticsAging(10);
		}

		// 一个商家一个订单一个商品
		OrderGroupVo groupVo1 = new OrderGroupVo();

		groupVo1.setSellerId(sellerId);
		groupVo1.setSellerLoginId(sellerName);

		groupVo1.setSellerCoupon(null);

		groupVo1.setOrders(Lists.newArrayList(orderVo));

		req.setOrderGroups(Lists.newArrayList(groupVo1));

		return req;
	}

	/**
	 * createOrderGroupVo
	 * 
	 * @param sellerId
	 * @param sellerName
	 * @return OrderGroupVo
	 */
	public static OrderGroupVo createOrderGroupVo(long sellerId,
			String sellerName) {

		OrderGroupVo groupVo = new OrderGroupVo();

		groupVo.setSellerId(sellerId);
		groupVo.setSellerLoginId(sellerName);
		groupVo.setSellerCoupon(null);

		groupVo.setOrders(Lists.newArrayList(createOrderVo(TestDataManager
				.getRandomUUID().toString())));

		return groupVo;
	}

	/**
	 * createOrderVo
	 * 
	 * @param productIds
	 * @return OrderVo
	 */
	public static OrderVo createOrderVo(List<ProductVo> productVoList) {

		OrderVo order = new OrderVo();

		order.setLogisticsType(LogisticsTypeEnum.OVERSEAS_DELIVERY);
		order.setAutoCancelOrderHours(BigDecimal.ONE);
		order.setLeaveWord("尽快发货！");

		List<OrderItemVo> items = new ArrayList<OrderItemVo>();

		for (ProductVo product : productVoList) {
			items.add(createOrderItemVo(product.getProductId(),
					product.getCatalogId()));
		}

		order.setOrderItems(items);
		return order;
	}

	/**
	 * 构建一个廉价商品
	 * 
	 * @param productVoList
	 * @return
	 */
	public static OrderVo createTestOrderVo(ProductVo productVo,
			BigDecimal price) {
		OrderVo order = new OrderVo();
		order.setLogisticsType(LogisticsTypeEnum.OVERSEAS_DELIVERY);
		order.setAutoCancelOrderHours(BigDecimal.ONE);
		order.setLeaveWord("尽快发货！");
		List<OrderItemVo> items = new ArrayList<OrderItemVo>();
		items.add(createTestOrderItemVo(productVo.getProductId(),
				productVo.getCatalogId(), price));
		order.setOrderItems(items);
		return order;
	}

	/**
	 * createOrderVo
	 * 
	 * @param productIds
	 * @return OrderVo
	 */
	public static OrderVo createOrderVo(String... productIds) {

		OrderVo order = new OrderVo();

		order.setLogisticsType(LogisticsTypeEnum.OVERSEAS_DELIVERY);
		order.setAutoCancelOrderHours(BigDecimal.ONE);
		order.setLeaveWord("尽快发货！");

		List<OrderItemVo> items = new ArrayList<OrderItemVo>();

		for (String productId : productIds) {
			items.add(createOrderItemVo(productId, TestDataManager
					.getRandomUUID().toString()));
		}

		order.setOrderItems(items);
		return order;
	}

	/**
	 * createOrderVo
	 * 
	 * @param productIds
	 * @return OrderVo
	 */
	public static OrderVo createOrderVo() {

		OrderVo order = new OrderVo();

//		long sellerId = 24635724;
//		
		long sellerId = 3383;
		String sellerName = "autotest1";

		ProductVo productVo1 = TradingCallService.creaderPro(sellerId,
				sellerName, 10);

		order.setLogisticsType(LogisticsTypeEnum.OVERSEAS_DELIVERY);
		order.setAutoCancelOrderHours(BigDecimal.ONE);
		order.setLeaveWord("尽快发货！");

		List<OrderItemVo> items = new ArrayList<OrderItemVo>();

		items.add(createOrderItemVo(productVo1.getProductId(),
				productVo1.getCatalogId()));

		order.setOrderItems(items);
		return order;
	}
	
	/**
	 * createOrderVo
	 * 
	 * @return OrderVo
	 */
	public static OrderVo createOrderVo(Long sellerId, String sellerName) {

		OrderVo order = new OrderVo();

		ProductVo productVo1 = TradingCallService.creaderPro(sellerId,
				sellerName, 10);

		order.setLogisticsType(LogisticsTypeEnum.OVERSEAS_DELIVERY);
		order.setAutoCancelOrderHours(BigDecimal.ONE);
		order.setLeaveWord("尽快发货！");

		List<OrderItemVo> items = new ArrayList<OrderItemVo>();

		items.add(createOrderItemVo(productVo1.getProductId(),
				productVo1.getCatalogId()));

		order.setOrderItems(items);
		return order;
	}

	/**
	 * createOrderItemVo
	 * 
	 * @param productId
	 * @return OrderItemVo
	 */
	public static OrderItemVo createOrderItemVo(String productId,
			String catalogId) {

		OrderItemVo orderItem = new OrderItemVo();

		BigDecimal price = new BigDecimal(new Random().nextInt(50) + 30);
		// BigDecimal price = new BigDecimal("1000");
		BigDecimal freight = new BigDecimal(new Random().nextInt(20) + 10);

		orderItem.setProductPrice(price);
		orderItem.setOriginalPrice(price);

		orderItem.setFreight(freight);
//		orderItem.setFreight(new BigDecimal("10000"));
//		orderItem.setProductNum(1);
		orderItem.setProductNum(new Random().nextInt(4) + 2);
		orderItem.setProductId(productId);
		orderItem.setCatalogId(catalogId);
		
//		orderItem.setProductId("p3525611");
//		orderItem.setCatalogId("c6408402");
		
		orderItem.setSalesType(SalesTypeEnum.AlreadyInStock);
		orderItem.setFirstCategoryId(1001);
		orderItem.setSecondCategoryId(1002);
		orderItem.setThirdCategoryId(1003);
		orderItem.setPreSale(false);
		orderItem.setProductRefundChannel(ProductRefundChannelEnum.None);
		orderItem
				.setPictureUrl("http://pic1.ymatou.com/G01/shangou/M00/39/85/rBBlD1k-U5eAMqEfAAIULSyYXWM521_104_78_n_w_o.jpg");
		orderItem.setSku("sku111");
		orderItem.setProperty("属性");
		orderItem.setBrandId(1234);
		orderItem.setProductName("自动化测试商品+" + TestDataManager.getRandomNum(10));
		orderItem.setProductRecordNo("9876");

		return orderItem;
	}

	/**
	 * 构建一个廉价商品
	 * 
	 * @param productId
	 * @param catalogId
	 * @param price
	 * @return
	 */
	public static OrderItemVo createTestOrderItemVo(String productId,
			String catalogId, BigDecimal price) {
		OrderItemVo orderItem = new OrderItemVo();
		BigDecimal freight = new BigDecimal(0);
		orderItem.setProductPrice(price);
		orderItem.setOriginalPrice(price);
		orderItem.setFreight(freight);
		orderItem.setProductNum(1);
		// orderItem.setProductNum(1000);
		orderItem.setProductId(productId);
		orderItem.setCatalogId(catalogId);
		orderItem.setSalesType(SalesTypeEnum.AlreadyInStock);
		orderItem.setFirstCategoryId(1001);
		orderItem.setSecondCategoryId(1002);
		orderItem.setThirdCategoryId(1003);
		orderItem.setPreSale(false);
		orderItem.setProductRefundChannel(ProductRefundChannelEnum.None);
		orderItem
				.setPictureUrl("http://pic1.ymatou.com/G01/shangou/M00/39/85/rBBlD1k-U5eAMqEfAAIULSyYXWM521_104_78_n_w_o.jpg");
		orderItem.setSku("sku111");
		orderItem.setProperty("属性");
		orderItem.setBrandId(1234);
		orderItem.setProductName("自动化测试商品+" + TestDataManager.getRandomNum(10));
		orderItem.setProductRecordNo("9876");
		return orderItem;
	}

	/**
	 * createActivityVo
	 * 
	 * @param activityId
	 * @return
	 */
	public static ActivityVo createActivityVo(long activityId) {

		ActivityVo activityVo = new ActivityVo();

		activityVo.setActivityId(activityId);
		activityVo.setActivityTemplateId(12345678);
		// activityVo.setProductInActivityId(4);

		return activityVo;
	}

	/**
	 * 
	 * @param userId
	 *            用户买家id
	 * @param sellerId
	 *            商家卖家id
	 * @param orderAmount
	 *            订单满多少
	 * @param sellerCouponValue
	 *            优惠券减多少
	 * @return CouponVo
	 */
	public static CouponVo createSellerCouponVo(Long userId, Long sellerId,
			BigDecimal orderAmount, BigDecimal sellerCouponValue) {

		String sellerCouponCode = TradingCallService.receiveSellerCoupon(
				userId, sellerId, orderAmount, sellerCouponValue);

		if (StringUtils.isEmpty(sellerCouponCode)) {
			return null;
		}

		return createCouponVo(sellerCouponCode, sellerCouponValue);

	}

	/**
	 * 
	 * @param userId
	 *            用户买家id
	 * @param orderAmount
	 *            订单满多少
	 * @param ymtCouponValue
	 *            优惠券减多少
	 * @return CouponVo
	 */
	public static CouponVo createYMTCouponVo(Long userId,
			BigDecimal orderAmount, BigDecimal ymtCouponValue) {

		String ymtCouponCode = TradingCallService.receiveYMTCoupon(userId,
				orderAmount, ymtCouponValue);

		if (StringUtils.isEmpty(ymtCouponCode)) {
			return null;
		}

		return createCouponVo(ymtCouponCode, ymtCouponValue);

	}

	/**
	 * createCouponVo
	 * 
	 * @return CouponVo
	 */
	public static CouponVo createCouponVo(String couponCode,
			BigDecimal couponValue) {

		CouponVo coupon = new CouponVo();

		coupon.setApplianceType(CouponApplianceTypeEnum.ALL);
		coupon.setCouponCode(couponCode);
		coupon.setCouponValue(couponValue);

		return coupon;

	}

	/**
	 * 领用商家优惠券
	 * 
	 * @param userId
	 * @param sellerId
	 * @param orderAmount
	 *            订单金额
	 * @param sellerCouponValue
	 *            优惠券减免金额
	 * @return
	 */
	public static String receiveSellerCoupon(Long userId, Long sellerId,
			BigDecimal orderAmount, BigDecimal sellerCouponValue) {

		if (IS_NEW_COUPON_SERVER) {

			return CouponServiceMCallServiceV2.receiveSellerCoupon(userId,
					sellerId, orderAmount, sellerCouponValue);
		} else {
			return CouponServiceMCallService.receiveSellerCoupon(userId,
					sellerId, orderAmount, sellerCouponValue);
		}

	}

	/**
	 * 领用YMT平台优惠券默认链接优惠券
	 * 
	 * @param userId
	 * @param orderAmount
	 * @param couponValue
	 * @return
	 */
	public static String receiveYMTCoupon(Long userId, BigDecimal orderAmount,
			BigDecimal couponValue) {

		if (IS_NEW_COUPON_SERVER) {
			return CouponServiceMCallServiceV2.receiveYMTCoupon(userId,
					orderAmount, couponValue);
		} else {
			return CouponServiceMCallService.receiveYMTCoupon(userId,
					orderAmount, couponValue);
		}
	}

	/**
	 * 根據userid 生成主单号
	 * 
	 * @param userId
	 * @return
	 */
	public static Long genMainOrderId(long userId) {

		long last4 = userId % 10000;

		GetSeqReq req = new GetSeqReq();
		GetSeqIdsCall call = new GetSeqIdsCall();

		long nativeId = 0L;

		req.setCount(1);
		req.setSeqName(String.format("main_%s", last4));

		call.setData(false, req);

		try {
			call.callService();

		} catch (Exception e) {

			e.printStackTrace();
		}

		nativeId = call.getids().get(0);

		nativeId += 100000;

		return nativeId * 10000 + last4;

	}

	public static JSONObject getProductInfo(String proId, int retrytimes) {
		try {

			if (retrytimes == 3)
				return null;

			JSONObject productInfo = GetProductInfoByProductIdCall
					.GetProductInfoByProductId(proId).getJSONObject("Data")
					.optJSONObject("Product");

			if (productInfo == null) {
				retrytimes += 1;

				Thread.sleep(5000);
				return getProductInfo(proId, retrytimes);
			}

			else
				return productInfo;

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 
	 * @param proId
	 * @param catalogId
	 * @param isActivityPro
	 *            是否是活动商品
	 * @return
	 */
	public static int getStockNum(String proId, String catalogId,
			boolean isActivityPro) {

		int stockNum = 0;

		try {
			// JSONObject productInfo = GetProductInfoByProductIdCall
			// .GetProductInfoByProductId(proId).getJSONObject("Data")
			// .getJSONObject("Product");
			JSONObject productInfo = getProductInfo(proId, 0);
			JSONArray catalogList = productInfo.getJSONArray("CatalogList");

			for (int i = 0; i < catalogList.length(); i++) {

				if (catalogId.equals(catalogList.getJSONObject(i).getString(
						"CatalogId"))) {

					// 如果是活动，返回活动库存
					if (isActivityPro) {
						stockNum = catalogList.getJSONObject(i).getInt(
								"ActivityStock");
					} else {
						stockNum = catalogList.getJSONObject(i).getInt(
								"CatalogStock");
					}

					break;

				}

			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return stockNum;

	}

	/**
	 * 创建普通商品
	 * 
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static TradingCallService.ProductVo creaderPro(Long sellerId,
			String sellerName, int stockNum) {

		Map updateMap = new HashMap();

		JSONObject productInfo = null;

		TradingCallService.ProductVo productVo = null;

		try {

			String proId = null;

			if (IS_NEW_PRO_SERVER) {

				AddSellerProductRequest addProdReq = ProductManagerCallServiceV2
						.initAddSellerProductRequest(Integer.parseInt(sellerId
								.toString()));
				addProdReq.getProduct().getCatalogList().get(0)
						.setStock(stockNum);
				addProdReq.getProduct().getCatalogList().get(1)
						.setStock(stockNum);
				addProdReq.getProduct().getCatalogList().get(0).setPrice(60);
				addProdReq.getProduct().getCatalogList().get(0).setVipPrice(10);
				addProdReq.getProduct().getCatalogList().get(0).setNewPrice(10);
				addProdReq.getProduct().getCatalogList().get(0)
						.setMarketPrice(80);
				proId = ProductManagerCallServiceV2
						.addNewProductOnSale(addProdReq)
						.getAsJsonObject("Data").get("ProductId").getAsString();

				Thread.sleep(3000);
				// 不要使用这个方法 会导致openfile过多
				// if (!YmtMongoDriverFactroy.isOnStage) {
				// new ProductsWapper().getByProductId(proId);
				// }

			} else {

				updateMap.put("Product->Catalogs[0]->Num", stockNum);

				// 商品上架
				/*
				 * String proId = SellerProductCallService
				 * .addNewProductOnSale(sellerId.intValue(), sellerName,
				 * updateMap).getJSONObject("Data")
				 * 
				 * .getString("ProductID");
				 */
				// 商品上架
				proId = SellerProductCallService
						.addNewProductNotOnSale(sellerId.intValue(),
								sellerName, updateMap).getJSONObject("Data")
						.getString("ProductID");

			}

			Thread.sleep(5000);

			// 手动同步一次商品
			YmatouEasyCall getProdCall = new YmatouEasyCall("", "GET", null);

			getProdCall
					.setUrl("http://productsync.iapi.ymatou.com/api/cache/mongocrud?ActionType=CreateProduct&ActivityId=0&TransactionId=322487428&ProductId="
							+ proId);
			getProdCall.setData("");
			getProdCall.callService();

			productInfo = getProductInfo(proId, 0);

			productVo = new ProductVo(proId, productInfo
					.getJSONArray("CatalogList").getJSONObject(0)
					.getString("CatalogId"));

			productVo.setStock(stockNum);

		} catch (Exception e) {

			e.printStackTrace();
			Logger.info(String.format("###############创建商家 sellerId %s，商品失败",
					sellerId));
		}

		return productVo;

	}

	/**
	 * 创建活动商品
	 * 
	 * @param sellerId
	 * @param sellerName
	 * @param stockNum
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static TradingCallService.ProductVo createActiverPro(Long sellerId,
			String sellerName, int stockNum) {

		TradingCallService.ProductVo productVo = null;

		// Map updateMap = new HashMap();

		// JSONObject addProductBean = JsonBeanHelper
		// .getJsonBean("com.ymatou.iapi.sellerproduct/AddNewSellerProduct/AddNewProductTpl_Tc11.json");
		//
		// JsonBeanHelper.updateJsonBean(addProductBean,
		// MapUtil.hashMap("UserID", sellerId, "LoginID", sellerName));

		String proId;

		try {

			/*
			 * Map updateMap = new HashMap();
			 * 
			 * updateMap.put("product->catalogList[0]->stock", stockNum);
			 * 
			 * updateMap.put("product->catalogList[0]->price", 100);
			 * updateMap.put("product->catalogList[0]->vipPrice", 100);
			 * updateMap.put("product->catalogList[0]->newPrice", 100);
			 * 
			 * AddSellerProductRequest addProdReq = AddProductCallService
			 * .getAddSellerProductRequestFromFile("单规格", updateMap);
			 * 
			 * addProdReq.setSellerId(sellerId.intValue());
			 * addProdReq.setSellerName(sellerName);
			 * 
			 * addProdReq.getProduct().setRemark("remark_test");
			 * 
			 * JSONObject ret = new AddSellerProductCall().callAndGetReturnData(
			 * false, addProdReq);
			 * 
			 * proId = ret.getJSONObject("Data").getString("ProductId");
			 */

			// proId = SellerProductCallService.addNewProduct(addProductBean)
			// .getJSONObject("Data").getString("ProductID");
			proId = TradingCallService.creaderPro(sellerId, sellerName,
					stockNum).getProductId();

			/*
			 * Map activityMap = new HashMap();
			 * 
			 * activityMap.put("ActivityTemplateId", 1);
			 */

			// 创建活动商品
			Map map = ProductPriceCallService.getProductAllowBuyWithActivity(
					sellerId.intValue(), proId, null);

			// 修改 活动商品规格 库存数量
			SellerProductCallService.updateActivityStockNum(
					sellerId.intValue(), proId, stockNum);
			// 查询活动商品 规格id
			JSONObject productInfo = getProductInfo(proId, 0);

			productVo = new ProductVo((String) map.get("productId"),
					productInfo.getJSONArray("CatalogList").getJSONObject(0)
							.getString("CatalogId"));

			productVo.setActivity((Integer) map.get("activityId"));
			productVo.setProductInActivityId((Integer) map
					.get("productInActivityId"));

			productVo.setActivityStock(stockNum);

		} catch (Exception e) {
			Logger.info(String.format("###############创建商家 sellerId %s，活动商品失败",
					sellerId));
			Logger.info(e.toString());
		}

		return productVo;

	}

	/**
	 * callPlaceOrderService
	 * 
	 * @param placeorderBean
	 * @return
	 */
	public static TradingServiceResp callPlaceOrderService(
			PlaceOrderReq placeOrderReq) {

		PlaceOrderCall placeorderCall = new PlaceOrderCall();

		TradingServiceResp orderResp = new TradingServiceResp();

		placeorderCall.setData(false, placeOrderReq);

		try {

			if (placeOrderReq.getMainOrderId() % 10000 != placeOrderReq
					.getUserId() % 10000) {

				// 设置主单号
				placeOrderReq.setMainOrderId(genMainOrderId(placeOrderReq
						.getUserId()));
			}

			placeorderCall.callService();

			// 如果下单失败，则重试3次，如果依然失败，则抛出exception
			int n = 0;
			retryPlaceOrder(placeorderCall, n);

			long userId = placeOrderReq.getUserId();

			orderResp.setUserId(userId);

			List<Long> orderIds = placeorderCall.getPlaceOrderResp()
					.getOrderIds();

			List<Order> orderList = new ArrayList<Order>();

			for (int i = 0; i < orderIds.size(); i++) {

				Order order = new Order();

				long orderId = orderIds.get(i);

				OrderShardingWapper orderShardingWapper = new OrderShardingWapper();

				OrderPo orderPo = orderShardingWapper
						.selectOrderbyOrderId(orderId);

				List<OrderDetailPo> orderDetailPoList = orderShardingWapper
						.selectOrderDetailbyOrderId(orderId);

				order.setOrderPo(orderPo);
				order.setOrderDetailPoList(orderDetailPoList);

				orderList.add(order);

			}

			if (placeOrderReq.getBizSource() != null) {

				orderResp.setBizId(placeOrderReq.getBizSource().getBizId());
			}

			orderResp.setOrderList(orderList);

			orderResp.setMainOrderId(placeOrderReq.getMainOrderId());

		} catch (Exception e) {

			e.printStackTrace();

		}

		// 下架由下单创建的商品
		Map<Long, List<String>> map = new HashMap<Long, List<String>>();

		placeOrderReq.getOrderGroups().forEach(
				group -> {

					long sellerId = group.getSellerId();

					List<String> proids = Lists.newArrayList();
					if (null != group.getOrders())
						group.getOrders().forEach(
								order -> order.getOrderItems()
										.forEach(
												item -> proids.add(item
														.getProductId())));

					map.put(sellerId, proids);

				});

		map.forEach((k, v) -> {

			try {

				ProductManagerCallServiceV2.batchSetProductOffSale(v,
						k.intValue());

			} catch (Exception e) {

				e.printStackTrace();

				Logger.info("下架由下单创建的商品出现异常！");
			}
		});

		return orderResp;
	}

	public static void retryPlaceOrder(PlaceOrderCall placeorderCall, int n) {

		try {

			if (n != 3 && placeorderCall.getCode() == 500) {

				placeorderCall.callService();
				n = n + 1;

				retryPlaceOrder(placeorderCall, n);
			} else if (n == 3)
				throw new Exception("下单失败，终止下单");

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 根据物流类型 下单
	 * 
	 * @param logisticsType
	 *            物流类型
	 * @return
	 */
	public static TradingServiceResp placeFenqileOrder(LogisticsTypeEnum logisticsType) {

		PlaceOrderReq placeorderBean = TradingCallService
				.buildStandPlaceOrderReq(false);

		OrderVo orderVo = placeorderBean.getOrderGroups().get(0).getOrders()
				.get(0);
		orderVo.setOrderType(4);
		OrderItemVo orderItemVo = orderVo.getOrderItems().get(0);

		orderVo.setLogisticsType(logisticsType);

		if (logisticsType.compareTo(LogisticsTypeEnum.BondedDelivery) == 0)
			orderItemVo.setBondedArea(BondedAreaEnum.ShenZhen);

		return TradingCallService.callPlaceOrderService(placeorderBean);

	}
	
	/**
	 * 根据满减包邮类型 下单
	 * 
	 * @param fullReductionFreeFreight
	 *            是否满减包邮
	 * @return
	 */
	public static TradingServiceResp placeOrder(Boolean fullReductionFreeFreight) {

		PlaceOrderReq placeorderBean = TradingCallService
				.buildStandPlaceOrderReq(false);

		OrderVo orderVo = placeorderBean.getOrderGroups().get(0).getOrders()
				.get(0);

		OrderItemVo orderItemVo = orderVo.getOrderItems().get(0);

		orderItemVo.setFullReductionFreeFreight(fullReductionFreeFreight);

		return TradingCallService.callPlaceOrderService(placeorderBean);
	}

	/**
	 * 根据物流类型 下单
	 * 
	 * @param logisticsType
	 *            物流类型
	 * @return
	 */
	public static TradingServiceResp placeOrder(LogisticsTypeEnum logisticsType) {

		PlaceOrderReq placeorderBean = TradingCallService
				.buildStandPlaceOrderReq(false);
		OrderVo orderVo = placeorderBean.getOrderGroups().get(0).getOrders()
				.get(0);

		OrderItemVo orderItemVo = orderVo.getOrderItems().get(0);

		orderVo.setLogisticsType(logisticsType);
		// 兼容老发货接口，时效设置为null
		orderVo.setLogisticsAging(20);

		if (logisticsType.compareTo(LogisticsTypeEnum.BondedDelivery) == 0)
			orderItemVo.setBondedArea(BondedAreaEnum.ShenZhen);

		return TradingCallService.callPlaceOrderService(placeorderBean);
	}

	/**
	 * 根据物流类型 下单
	 * 
	 * @param logisticsType
	 *            物流类型
	 * @return
	 */
	public static TradingServiceResp placeOrder(
			LogisticsTypeEnum logisticsType, Integer packageDeliveryType) {

		PlaceOrderReq placeorderBean = TradingCallService
				.buildStandPlaceOrderReq(false);

		OrderVo orderVo = placeorderBean.getOrderGroups().get(0).getOrders()
				.get(0);

		orderVo.setLogisticsType(logisticsType);
		orderVo.setPackageDeliveryType(packageDeliveryType);

		return TradingCallService.callPlaceOrderService(placeorderBean);
	}

	/**
	 * @deprecated
	 *这个方法容易用错 注意
	 * 根据物流类型 下单
	 * 
	 * @param logisticsType
	 *            物流类型
	 * @return
	 */
	public static TradingServiceResp placeOrder(Integer packageDeliveryType) {

		PlaceOrderReq placeorderBean = TradingCallService
				.buildStandPlaceOrderReq(false);

		OrderVo orderVo = placeorderBean.getOrderGroups().get(0).getOrders()
				.get(0);

		orderVo.setLogisticsType(LogisticsTypeEnum.OVERSEAS_DELIVERY);
		orderVo.setPackageDeliveryType(packageDeliveryType);

		return TradingCallService.callPlaceOrderService(placeorderBean);
	}
	
	/**
	 * 根据ubuy信息 下单
	 * 
	 * @param ubuyUserVo
	 *            ubuy信息
	 * @return
	 */
	public static TradingServiceResp placeOrderWithUbuy(UbuyUserVo ubuyUserVo) {

		PlaceOrderReq placeorderBean = TradingCallService
				.buildStandPlaceOrderReq(false);
		
		placeorderBean.setUbuyUserVo(ubuyUserVo);

		return TradingCallService.callPlaceOrderService(placeorderBean);
	}
	
	/**
	 * @return
	 */
	public static TradingServiceResp placeOrderWithThirdPartyPromotion() {

		PlaceOrderReq placeorderBean = TradingCallService
				.buildStandPlaceOrderReq(false);

		ThirdPartyPromotionVo thirdPartyPromotionVo = new ThirdPartyPromotionVo();

		thirdPartyPromotionVo.setThirdPartyName(TestDataManager.randomStr(10)
				+ "thirdPartyName");
		
//		thirdPartyPromotionVo.setThirdPartyName("91d6320a-9925-4642-8cac-cb3516894f07");
		thirdPartyPromotionVo.setThirdPartyPromoter(TestDataManager
				.randomStr(10) + "thirdPartyPromoter");
		thirdPartyPromotionVo.setThirdPartySubPlatform(TestDataManager
				.randomStr(10) + "thirdPartySubPlatform");
		thirdPartyPromotionVo.setOuterParam(TestDataManager.randomStr(10)
				+ "outerParam");

		placeorderBean.setThirdPartyPromotion(thirdPartyPromotionVo);
		placeorderBean.setOuterPromotionId(thirdPartyPromotionVo
				.getThirdPartyName());

		return TradingCallService.callPlaceOrderService(placeorderBean);
	}
	
	/**
	 * 根据graphicProduct信息 下单
	 * 
	 * @return
	 */
	public static TradingServiceResp placeOrderWithGraphicProduct(
			Boolean graphicProduct) {

		PlaceOrderReq placeorderBean = TradingCallService
				.buildStandPlaceOrderReq(false);

		placeorderBean.getOrderGroups().get(0).getOrders().get(0)
				.getOrderItems().get(0).setGraphicProduct(true);

		return TradingCallService.callPlaceOrderService(placeorderBean);
	}
	
	/**
	 * 根据luxury信息 下单
	 * 
	 * @return
	 */
	public static TradingServiceResp placeOrderWithLuxury(
			Boolean luxury) {

		PlaceOrderReq placeorderBean = TradingCallService
				.buildStandPlaceOrderReq(false);

		placeorderBean.getOrderGroups().get(0).getOrders().get(0)
				.getOrderItems().get(0).setLuxury(luxury);

		return TradingCallService.callPlaceOrderService(placeorderBean);
	}
	
	/**
	 * 根据物流类型 下单
	 * 
	 * @param logisticsType
	 *            物流类型
	 * @return
	 */
	public static TradingServiceResp placeOrder(BigDecimal rebatePaidAmount) {

		PlaceOrderReq placeorderBean = TradingCallService
				.buildStandPlaceOrderReq(false);
		
		placeorderBean.setRebatePaidAmount(rebatePaidAmount);

		return TradingCallService.callPlaceOrderService(placeorderBean);

	}

	/**
	 * 根据bookingConfirmOrderIds 下单
	 * 
	 * @param bookingConfirmOrderIds
	 *            预定订单列表
	 * @return
	 */
	public static TradingServiceResp placeOrder(
			List<Long> bookingConfirmOrderIds) {

		PlaceOrderReq placeorderBean = TradingCallService
				.buildStandPlaceOrderReq(false);

		placeorderBean.getOrderGroups().get(0)
				.setBookingConfirmOrderIds(bookingConfirmOrderIds);

		return TradingCallService.callPlaceOrderService(placeorderBean);
	}

	/**
	 * 根据物流类型 下单
	 * 
	 * @param logisticsType
	 *            物流类型
	 * @param sellerId
	 *            买手id
	 * @param sellerName
	 *            买手名称
	 * @return
	 */
	public static TradingServiceResp placeOrder(
			LogisticsTypeEnum logisticsType, long sellerId, String sellerName) {

		PlaceOrderReq placeorderBean = TradingCallService
				.buildStandPlaceOrderReq(false, sellerId, sellerName);

		OrderVo orderVo = placeorderBean.getOrderGroups().get(0).getOrders()
				.get(0);

		orderVo.setLogisticsType(logisticsType);

		return TradingCallService.callPlaceOrderService(placeorderBean);

	}
	
	/**
	 * 根据物流类型 下单
	 * 
	 * @param logisticsType
	 *            物流类型
	 * @param sellerId
	 *            买手id
	 * @param sellerName
	 *            买手名称
	 * @return
	 */
	public static TradingServiceResp placeOrderWithOfficialLogistics(
			LogisticsTypeEnum logisticsType, long sellerId, String sellerName) {

		PlaceOrderReq placeorderBean = TradingCallService
				.buildStandPlaceOrderReq(false, sellerId, sellerName);

		OrderVo orderVo = placeorderBean.getOrderGroups().get(0).getOrders()
				.get(0);

		orderVo.setLogisticsType(logisticsType);
		orderVo.setOfficialLogistics(true);

		return TradingCallService.callPlaceOrderService(placeorderBean);

	}
	
	/**
	 * 根据物流类型 下单
	 * 
	 * @param logisticsType
	 *            物流类型
	 * @param sellerId
	 *            买手id
	 * @param sellerName
	 *            买手名称
	 * @return
	 */
	public static TradingServiceResp placeOrderWithOfficialLogistics(
			LogisticsTypeEnum logisticsType) {

		PlaceOrderReq placeorderBean = TradingCallService
				.buildStandPlaceOrderReq(false);

		OrderVo orderVo = placeorderBean.getOrderGroups().get(0).getOrders()
				.get(0);

		orderVo.setLogisticsType(logisticsType);
		orderVo.setOfficialLogistics(true);

		return TradingCallService.callPlaceOrderService(placeorderBean);

	}

	/**
	 * 根据userId 下单
	 * 
	 * @param userId
	 *            买家id
	 * @return
	 */
	public static TradingServiceResp placeOrder(int userId) {

		PlaceOrderReq placeorderBean = TradingCallService
				.buildStandPlaceOrderReq(false, false, userId);

		return TradingCallService.callPlaceOrderService(placeorderBean);

	}

	/**
	 * 创建一个订单
	 * 
	 * @param isBargainGroup
	 *            是否是砍价团
	 * @param isUserCoupon
	 *            是否使用优惠券
	 * @return
	 */
	public static TradingServiceResp placeOrder1(boolean isBargainGroup,
			boolean isUserCoupon) {

		PlaceOrderReq placeOrderReq = TradingCallService
				.buildStandPlaceOrderReq(isBargainGroup);

		long userId = placeOrderReq.getUserId();

		placeOrderReq.getOrderGroups().get(0).getOrders().get(0).getOrderItems().get(0).setBuyDailyLimit(true);
		
		// 买手1 订单组
		OrderGroupVo groupVo1 = placeOrderReq.getOrderGroups().get(0);

		long sellerId = groupVo1.getSellerId();

		if (isUserCoupon) {

			// 平台券
			placeOrderReq.setYmatouCoupon(TradingCallService.createYMTCouponVo(
					userId, BigDecimal.TEN, BigDecimal.ONE));
			// 商家券
			CouponVo sellerCoupon1 = TradingCallService.createSellerCouponVo(
					userId, sellerId, new BigDecimal(30), BigDecimal.TEN);

			groupVo1.setSellerCoupon(sellerCoupon1);
		}

		return TradingCallService.callPlaceOrderService(placeOrderReq);

	}
	
	public static boolean isAnliMember(Integer orderType) {
		
		if (orderType == null)
			return false;
		else if (orderType == 2 || orderType == 3)
			return true;
		else 
			return false;
	}
	
	/**
	 * 创建一个安利会订单
	 * 
	 * @param rebateAmount
	 *            返点金额
	 * @param isUserCoupon
	 *            是否使用优惠券
	 * @param orderType
	 *            订单类型
	 * @return
	 * @throws Exception 
	 */
	public static TradingServiceResp placeAnlihuiOrder(BigDecimal rebateAmount, boolean isUserCoupon) throws Exception {

		return placeAnlihuiOrder(rebateAmount, isUserCoupon, 3);
	}
	
	/**
	 * 创建一个安利会订单
	 * 
	 * @param rebateAmount
	 *            返点金额
	 * @param isUserCoupon
	 *            是否使用优惠券
	 * @param orderType
	 *            订单类型
	 * @return
	 * @throws Exception 
	 */
	public static TradingServiceResp placeAnlihuiOrder(BigDecimal rebateAmount, boolean isUserCoupon, int orderType) throws Exception {

		return placeAnlihuiOrder(rebateAmount, isUserCoupon, 5678L, orderType);
	}
	
	/**
	 * 创建一个安利会订单
	 * @param rebateAmount
	 * @param isUserCoupon
	 * @param orderType
	 * @param rebateRatios
	 * @return
	 * @throws Exception 
	 */
	public static TradingServiceResp placeAnlihuiOrder(BigDecimal rebateAmount,
			boolean isUserCoupon, int orderType, List<BigDecimal> rebateRatios) throws Exception {

		return placeAnlihuiOrder(20238699L, rebateAmount, isUserCoupon, 2002L,
				orderType, rebateRatios, null);
	}
	
	/**
	 * 创建一个安利会订单
	 * 
	 * @param rebateAmount
	 *            返点金额
	 * @param isUserCoupon
	 *            是否使用优惠券
	 * @param memeberId
	 *            邀请人id          
	 * @param orderType
	 *            订单类型
	 * @return
	 * @throws Exception 
	 */
	public static TradingServiceResp placeAnlihuiOrder(BigDecimal rebateAmount,
			boolean isUserCoupon, Long memeberId, int orderType) throws Exception {

		return placeAnlihuiOrder(20238699L, rebateAmount, isUserCoupon,
				memeberId, orderType, Arrays.asList(new BigDecimal("0.1982"),
						new BigDecimal("0.3123")), null);
	}

	/**
	 * 创建一个安利会订单
	 * @param userId
	 * @param rebateAmount
	 * @param isUserCoupon
	 * @param memeberId
	 * @param orderType
	 * @return
	 * @throws Exception 
	 */
	public static TradingServiceResp placeAnlihuiOrder(long userId, BigDecimal rebateAmount,
			boolean isUserCoupon, Long memeberId, int orderType) throws Exception {

		return placeAnlihuiOrder(userId, rebateAmount, isUserCoupon, memeberId,
				orderType, Arrays.asList(new BigDecimal("0.1982"),
						new BigDecimal("0.3123")), null);
	}
	
	/**
	 * 创建一个安利会订单
	 * @param userId
	 * @param rebateAmount
	 * @param isUserCoupon
	 * @param memeberId
	 * @param orderType
	 * @param linkPayAnliOrderId
	 * @return
	 * @throws Exception 
	 */
	public static TradingServiceResp placeAnlihuiOrder(long userId, BigDecimal rebateAmount,
			boolean isUserCoupon, Long memeberId, int orderType, Long linkPayAnliOrderId) throws Exception {

		return placeAnlihuiOrder(userId, rebateAmount, isUserCoupon, memeberId,
				orderType, Arrays.asList(new BigDecimal("0.1982"),
						new BigDecimal("0.3123")), linkPayAnliOrderId);
	}
	
	/**
	 * 创建一个安利会订单
	 * @param userId
	 *            买家id
	 * @param rebateAmount
	 *            返点金额
	 * @param isUserCoupon
	 *            是否使用优惠券
	 * @param memeberId
	 *            邀请人id          
	 * @param orderType
	 *            订单类型
	 * @return
	 * @throws Exception 
	 */
	public static TradingServiceResp placeAnlihuiOrder(long userId, BigDecimal rebateAmount,
			boolean isUserCoupon, Long memeberId, int orderType, List<BigDecimal> rebateRatios, Long linkPayAnliOrderId) throws Exception {

		PlaceOrderReq placeOrderReq = TradingCallService
				.buildStandPlaceOrderReq(false);
		
//		PlaceOrderReq placeOrderReq = TradingCallService
//				.buildStandPlaceOrderReq(false, false,
//				Long.valueOf(EnvSetup.getData("BuyUserId")),
//				3383L,
//				String.valueOf(EnvSetup.getData("autotest_sellerName1")));

		placeOrderReq.setUserId(userId);

		placeOrderReq.setShareUserId(memeberId);
		
//		placeOrderReq.setOrderSource(OrderSourceEnum.C2CWechat);
		
		//如果买家的rebateAmount不足，则充值
		if (rebateAmount.compareTo(BigDecimal.ZERO) > 0) {
			
			String accountid1 = AccountCallServiceV2.getAccountId((int)userId, 5);
			
			if (AccountCallServiceV2.getAccountBalance((int)userId, 5).compareTo(rebateAmount) == -1)
				AccountCallServiceV2.resetAccount(accountid1, rebateAmount, new BigDecimal(0));
			
			placeOrderReq.setRebatePaidAmount(rebateAmount);
		}
			
		// 买手1 订单组
		OrderGroupVo groupVo1 = placeOrderReq.getOrderGroups().get(0);

		OrderVo orderVo = placeOrderReq.getOrderGroups().get(0).getOrders()
				.get(0);
		OrderItemVo orderItemVo = placeOrderReq.getOrderGroups().get(0)
				.getOrders().get(0).getOrderItems().get(0);
		
		if (null != linkPayAnliOrderId)
			orderVo.setLinkPayAnliOrderId(linkPayAnliOrderId);
		
		if (orderType == 2 || orderType == 3)
			orderVo.setLogisticsType(LogisticsTypeEnum.AutoDelivery);
		
		orderVo.setOrderType(orderType);

		orderItemVo.setSellerRebateRatio(rebateRatios.get(0));
		orderItemVo.setRebateRatio(rebateRatios.get(1));
		orderItemVo.setAnliPromotionRuleId("autotestAnliPromotionRuleId");

		long sellerId = groupVo1.getSellerId();

		if (isUserCoupon) {

			// 平台券
			placeOrderReq.setYmatouCoupon(TradingCallService.createYMTCouponVo(
					userId, BigDecimal.TEN, BigDecimal.ONE));
			// 商家券
			CouponVo sellerCoupon1 = TradingCallService.createSellerCouponVo(
					userId, sellerId, new BigDecimal(30), BigDecimal.TEN);

			groupVo1.setSellerCoupon(sellerCoupon1);
		}

		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}
	
	/**
	 * 创建一个最大返点金额的安利会订单
	 * @param userId
	 *            买家id
	 * @param rebateAmount
	 *            返点金额
	 * @param isUserCoupon
	 *            是否使用优惠券
	 * @param memeberId
	 *            邀请人id          
	 * @param orderType
	 *            订单类型
	 * @return
	 * @throws Exception 
	 */
	public static TradingServiceResp placeMaxRebateAmountAnlihuiOrder(BigDecimal rebateAmount,
			long memeberId, int orderType, List<BigDecimal> rebateRatios) throws Exception {

		int userId = new OrderCallService().createNewUser();
		
		PlaceOrderReq placeOrderReq = TradingCallService
				.buildStandPlaceOrderReq(false);

		placeOrderReq.setUserId(userId);

		BigDecimal rebatePaidAmount = BigDecimal.TEN;

		placeOrderReq.setShareUserId(memeberId);
		
		if (rebateAmount.compareTo(BigDecimal.ZERO) > 0)
			placeOrderReq.setRebatePaidAmount(rebatePaidAmount);

		// 买手1 订单组
		OrderGroupVo groupVo1 = placeOrderReq.getOrderGroups().get(0);

		OrderVo orderVo = groupVo1.getOrders()
				.get(0);
		OrderItemVo orderItemVo = placeOrderReq.getOrderGroups().get(0)
				.getOrders().get(0).getOrderItems().get(0);

		orderVo.setOrderType(orderType);

		orderItemVo.setProductPrice(new BigDecimal("5000"));
		orderItemVo.setSellerRebateRatio(rebateRatios.get(0));
		orderItemVo.setRebateRatio(rebateRatios.get(1));
		orderItemVo.setAnliPromotionRuleId("autotestAnliPromotionRuleId");

		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}
	
	/**
	 * 创建一个安利会订单,包含多个商品
	 * 
	 * @param rebateAmount
	 *            返点金额
	 * @param isUserCoupon
	 *            是否使用优惠券
	 * @param orderType
	 *            订单类型
	 * @return
	 */
	public static TradingServiceResp placeMultiProAnlihuiOrder(
			BigDecimal rebateAmount, boolean isUserCoupon, int orderType) {

		return placeMultiProAnlihuiOrder(rebateAmount, isUserCoupon, 5678L,
				orderType);
	}
	
	/**
	 * 创建一个安利会订单,包含多个商品
	 * 
	 * @param rebateAmount
	 *            返点金额
	 * @param isUserCoupon
	 *            是否使用优惠券
	 * @param orderType
	 *            订单类型
	 * @param shareUserId
	 *            推介人id
	 * @return
	 */
	public static TradingServiceResp placeMultiProAnlihuiOrder(
			BigDecimal rebateAmount, boolean isUserCoupon, long shareUserId, int orderType) {

		return placeMultiProAnlihuiOrder(rebateAmount, isUserCoupon, shareUserId, orderType, true);
	}
	
	/**
	 * 创建一个安利会订单,包含多个商品
	 * 
	 * @param rebateAmount
	 *            返点金额
	 * @param isUserCoupon
	 *            是否使用优惠券
	 * @param orderType
	 *            订单类型
	 * @param shareUserId
	 *            推介人id
	 * @return
	 */
	public static TradingServiceResp placeMultiProAnlihuiOrder(
			BigDecimal rebateAmount, boolean isUserCoupon, long shareUserId, int orderType, boolean allAnlihui) {

		PlaceOrderReq placeOrderReq = TradingCallService
				.buildStandPlaceOrderReq(false);

		long userId = placeOrderReq.getUserId();

		BigDecimal rebatePaidAmount = BigDecimal.TEN;

		placeOrderReq.setShareUserId(shareUserId);
		placeOrderReq.setRebatePaidAmount(rebatePaidAmount);

		// 买手1 订单组
		OrderGroupVo groupVo1 = placeOrderReq.getOrderGroups().get(0);

		OrderVo orderVo = placeOrderReq.getOrderGroups().get(0).getOrders()
				.get(0);
		orderVo.setOrderType(orderType);
		
		OrderItemVo orderItemVo = placeOrderReq.getOrderGroups().get(0)
				.getOrders().get(0).getOrderItems().get(0);

		orderItemVo.setSellerRebateRatio(new BigDecimal("0.1982"));
		orderItemVo.setRebateRatio(new BigDecimal("0.3123"));
		orderItemVo.setAnliPromotionRuleId("autotestAnliPromotionRuleId");
		
		// 创建一个普通商品
		TradingCallService.ProductVo pro = TradingCallService.creaderPro(
				Long.valueOf(EnvSetup.getData("autotest_seller1")),
				String.valueOf(EnvSetup.getData("autotest_sellerName1")), 100);
		
		//创建第二个orderItem
		OrderItemVo orderItemVo2 = TradingCallService.createOrderItemVo(
				pro.getProductId(), pro.getCatalogId());
		
		if (allAnlihui) {
			
			orderItemVo2.setSellerRebateRatio(new BigDecimal("0.1123"));
			orderItemVo2.setRebateRatio(new BigDecimal("0.1982"));
			orderItemVo2.setAnliPromotionRuleId("autotestAnliPromotionRuleId");
		}
		
		orderVo.getOrderItems().add(orderItemVo2);

		if (isUserCoupon) {

			// 平台券
			placeOrderReq.setYmatouCoupon(TradingCallService.createYMTCouponVo(
					userId, BigDecimal.TEN, BigDecimal.ONE));
			// 商家券
			CouponVo sellerCoupon1 = TradingCallService.createSellerCouponVo(
					userId, Long.valueOf(EnvSetup.getData("autotest_seller1")),
					new BigDecimal(30), BigDecimal.TEN);

			groupVo1.setSellerCoupon(sellerCoupon1);
		}

		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}
	
	/**
	 * 创建一个安利会订单,包含多个商品
	 * 
	 * @param rebateAmount
	 *            返点金额
	 * @param isUserCoupon
	 *            是否使用优惠券
	 * @param orderType
	 *            订单类型
	 * @param shareUserId
	 *            推介人id
	 * @return
	 */
	public static TradingServiceResp placeMultiProAnlihuiOrder(
			long userId, Long shareUserId, int orderType, boolean allAnlihui) {

		PlaceOrderReq placeOrderReq = TradingCallService
				.buildStandPlaceOrderReq(false);

		placeOrderReq.setUserId(userId);
		placeOrderReq.setShareUserId(shareUserId);

		OrderVo orderVo = placeOrderReq.getOrderGroups().get(0).getOrders()
				.get(0);
		orderVo.setOrderType(orderType);
		
		OrderItemVo orderItemVo = placeOrderReq.getOrderGroups().get(0)
				.getOrders().get(0).getOrderItems().get(0);

		orderItemVo.setSellerRebateRatio(new BigDecimal("0.1982"));
		orderItemVo.setRebateRatio(new BigDecimal("0.3123"));
		orderItemVo.setAnliPromotionRuleId("autotestAnliPromotionRuleId");
		
		// 创建一个普通商品
		TradingCallService.ProductVo pro = TradingCallService.creaderPro(
				Long.valueOf(EnvSetup.getData("autotest_seller1")),
				String.valueOf(EnvSetup.getData("autotest_sellerName1")), 100);
		
		//创建第二个orderItem
		OrderItemVo orderItemVo2 = TradingCallService.createOrderItemVo(
				pro.getProductId(), pro.getCatalogId());
		
		if (allAnlihui) {
			
			orderItemVo2.setSellerRebateRatio(new BigDecimal("0.1123"));
			orderItemVo2.setRebateRatio(new BigDecimal("0.1982"));
			orderItemVo2.setAnliPromotionRuleId("autotestAnliPromotionRuleId");
		}
		
		orderVo.getOrderItems().add(orderItemVo2);


		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}
	
	/**
	 * 创建多个安利会订单
	 * 
	 * @param rebateAmount
	 *            返点金额
	 * @param isUserCoupon
	 *            是否使用优惠券
	 * @return
	 */
	public static TradingServiceResp placeMultiAnlihuiOrder(BigDecimal rebateAmount, boolean isUserCoupon) {

		PlaceOrderReq placeOrderReq = TradingCallService
				.buildStandPlaceOrderReq(false);

		long userId = placeOrderReq.getUserId();
		
		BigDecimal rebatePaidAmount = BigDecimal.TEN;

		placeOrderReq.setShareUserId(5678L);
		placeOrderReq.setRebatePaidAmount(rebatePaidAmount);
		
		// 买手1 订单组
		OrderGroupVo groupVo1 = placeOrderReq.getOrderGroups().get(0);
		
		OrderVo orderVo = placeOrderReq.getOrderGroups().get(0).getOrders().get(0);
		OrderItemVo orderItemVo = placeOrderReq.getOrderGroups().get(0).getOrders().get(0).getOrderItems().get(0);
		
		orderVo.setOrderType(3);
		orderVo.setLogisticsType(LogisticsTypeEnum.AutoDelivery);
		
		List<OrderVo> orderVoList = placeOrderReq.getOrderGroups().get(0)
				.getOrders();

		orderItemVo.setProductNum(5);
		
		// 创建一个普通商品
		TradingCallService.ProductVo pro = TradingCallService.creaderPro(
				Long.valueOf(EnvSetup.getData("autotest_seller1")),
				String.valueOf(EnvSetup.getData("autotest_sellerName1")), 100);
		
		OrderVo orderVo2 = TradingCallService.createOrderVo(Arrays.asList(pro));
		
		// 创建一个普通商品
		TradingCallService.ProductVo pro2 = TradingCallService.creaderPro(
				Long.valueOf(EnvSetup.getData("autotest_seller1")),
				String.valueOf(EnvSetup.getData("autotest_sellerName1")), 100);

		// 创建第二个orderItem
		OrderItemVo orderItemVo2 = TradingCallService.createOrderItemVo(
				pro2.getProductId(), pro2.getCatalogId());

		orderItemVo2.setSellerRebateRatio(new BigDecimal("0.1123"));
		orderItemVo2.setRebateRatio(new BigDecimal("0.1982"));
		orderItemVo2.setAnliPromotionRuleId("autotestAnliPromotionRuleId");

		orderVo2.getOrderItems().add(orderItemVo2);

		orderVoList.addAll(Lists.newArrayList(orderVo2));

		long sellerId = groupVo1.getSellerId();

		if (isUserCoupon) {

			// 平台券
			placeOrderReq.setYmatouCoupon(TradingCallService.createYMTCouponVo(
					userId, BigDecimal.TEN, BigDecimal.ONE));
			// 商家券
			CouponVo sellerCoupon1 = TradingCallService.createSellerCouponVo(
					userId, sellerId, new BigDecimal(30), BigDecimal.TEN);

			groupVo1.setSellerCoupon(sellerCoupon1);
		}

		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}
	
	/**
	 * 创建多个安利会订单
	 * 
	 * @param rebateAmount
	 *            返点金额
	 * @param isUserCoupon
	 *            是否使用优惠券
	 * @param isAllRebateOrder
	 *            是否都是安利会订单
	 * @return
	 */
	public static TradingServiceResp placeMultiProAnlihuiMultiOrder(
			long userId, long shareUserId, boolean isAllRebateOrder) {

		PlaceOrderReq placeOrderReq = TradingCallService
				.buildStandPlaceOrderReq(true);

		placeOrderReq.setUserId(userId);
		placeOrderReq.setShareUserId(shareUserId);
		
		OrderVo orderVo = placeOrderReq.getOrderGroups().get(0).getOrders().get(0);
		OrderItemVo orderItemVo = placeOrderReq.getOrderGroups().get(0).getOrders().get(0).getOrderItems().get(0);
		
		orderVo.setOrderType(0);
		
		orderItemVo.setSellerRebateRatio(new BigDecimal("0.1982"));
		orderItemVo.setRebateRatio(new BigDecimal("0.3123"));
		orderItemVo.setAnliPromotionRuleId("autotestAnliPromotionRuleId");
		
		OrderItemVo orderItemVo1 = TradingCallService.createOrderItemVo(TestDataManager
				.getRandomUUID().toString(), TestDataManager
				.getRandomUUID().toString());
		
		orderItemVo1.setSellerRebateRatio(new BigDecimal("0.1982"));
		orderItemVo1.setRebateRatio(new BigDecimal("0.3123"));
		orderItemVo1.setAnliPromotionRuleId("autotestAnliPromotionRuleId");
		
		List<OrderVo> orderVoList = placeOrderReq.getOrderGroups().get(0)
				.getOrders();
		
		orderVoList.get(0).getOrderItems().add(orderItemVo1);
		
		OrderVo orderVo2 = TradingCallService.createOrderVo(TestDataManager
				.getRandomUUID().toString());
		
		if (isAllRebateOrder) {
			
			OrderItemVo orderItemVo3 = orderVo2.getOrderItems().get(0);
			
			orderItemVo3.setSellerRebateRatio(new BigDecimal("0.1982"));
			orderItemVo3.setRebateRatio(new BigDecimal("0.3123"));
			orderItemVo3.setAnliPromotionRuleId("autotestAnliPromotionRuleId");
			
			orderVo2.setOrderType(0);
		}
		
		orderVoList.add(orderVo2);

		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}
	
	/**
	 * 创建安利会会员和安利会普通商品订单组
	 * @return
	 */
	public static TradingServiceResp placeAnlihuiMemberAndAnlihuiNormalOrderGroup(
			long userId, long shareUserId, int orderType) {

		PlaceOrderReq placeOrderReq = TradingCallService
				.buildStandPlaceOrderReq(true);
		
		placeOrderReq.setUserId(userId);

		placeOrderReq.setShareUserId(shareUserId);
		
		OrderVo orderVo = placeOrderReq.getOrderGroups().get(0).getOrders().get(0);
		OrderItemVo orderItemVo = placeOrderReq.getOrderGroups().get(0).getOrders().get(0).getOrderItems().get(0);
		
		orderVo.setOrderType(0);
		
		orderItemVo.setSellerRebateRatio(new BigDecimal("0.1982"));
		orderItemVo.setRebateRatio(new BigDecimal("0.3123"));
		orderItemVo.setAnliPromotionRuleId("autotestAnliPromotionRuleId");
		
		OrderGroupVo orderGroupVo2 = TradingCallService.createOrderGroupVo(3383L, "wesper");
		ProductVo productVo = TradingCallService.creaderPro(3383L, "wesper", 10);
		OrderVo orderVo2 = TradingCallService.createOrderVo(Arrays.asList(productVo));
		
		orderVo2.setOrderType(orderType);
		
		orderGroupVo2.getOrders().remove(0);
		orderGroupVo2.getOrders().add(orderVo2);	
		
		placeOrderReq.getOrderGroups().add(orderGroupVo2);

		return TradingCallService.callPlaceOrderService(placeOrderReq);

	}
	
	/**
	 * 创建安利会会员和安利会普通商品订单
	 * @return
	 */
	public static TradingServiceResp placeAnlihuiMemberAndAnlihuiNormalOrder(
			long userId, long shareUserId, int orderType) {

		PlaceOrderReq placeOrderReq = TradingCallService
				.buildStandPlaceOrderReq(false);
		
		placeOrderReq.setUserId(userId);

		placeOrderReq.setShareUserId(shareUserId);
		
		OrderGroupVo orderGroupVo = placeOrderReq.getOrderGroups().get(0);
		OrderVo orderVo = placeOrderReq.getOrderGroups().get(0).getOrders().get(0);
		OrderItemVo orderItemVo = orderVo.getOrderItems().get(0);
		
		orderVo.setOrderType(0);
		
		orderItemVo.setSellerRebateRatio(new BigDecimal("0.1982"));
		orderItemVo.setRebateRatio(new BigDecimal("0.3123"));
		orderItemVo.setAnliPromotionRuleId("autotestAnliPromotionRuleId");
		
		ProductVo productVo = TradingCallService.creaderPro(orderGroupVo.getSellerId(), "", 10);
		OrderVo orderVo2 = TradingCallService.createOrderVo(Arrays.asList(productVo));
		
		orderVo2.setLogisticsType(LogisticsTypeEnum.AutoDelivery);
		
		orderVo2.setOrderType(orderType);
		
		orderGroupVo.getOrders().add(orderVo2);

		return TradingCallService.callPlaceOrderService(placeOrderReq);

	}

	/**
	 * 初始化一个订单userId购买1件sellerId的proId商品
	 * 
	 * @param userId
	 * @param sellerId
	 * @param proId
	 * @param price
	 * @return
	 * @throws Exception
	 */
	public static PlaceOrderReq initPlaceTestOrder(Long userId, Long sellerId,
			String proId, BigDecimal price) throws Exception {
		// long userId=Long.valueOf(EnvSetup.getData("BuyUserId"));
		// long sellerId=Long.valueOf(EnvSetup.getData("autotest_seller1"));
		String sellerName = JUserCallService.GetUserInfo(userId.intValue())
				.getLoginId();
		Integer addressId = JUserCallService
				.getAddressInfoList(userId.intValue()).get(0).getiAddressId();
		PlaceOrderReq req = new PlaceOrderReq();
		req.setAddressId((long)addressId);
		req.setRecvMobile("136" + TestDataManager.getRandomNum(8));
		req.setRecvName("testUser");
		req.setAppId("ymt autotest");
		req.setUserId(userId);
		req.setAddress("上海 静安 江场三路");
		req.setPostCode("200000");
		req.setEquipmentId(TestDataManager.getRandomUUID().toString());
		req.setDeviceId(TestDataManager.getRandomUUID().toString());
		req.setSourceIp(TestDataManager.getRandomIp());
		req.setAppTerminalSource(AppTerminalSourceEnum.Phone);
		req.setOrderSource(OrderSourceEnum.Wechat);
		req.setTerminalSource(TerminalSourceEnum.Android);
		req.setMainOrderId(genMainOrderId(req.getUserId()));
		JSONObject productInfo = GetProductInfoByProductIdCall
				.GetProductInfoByProductId(proId).getJSONObject("Data")
				.getJSONObject("Product");
		ProductVo productVo = new ProductVo(proId, productInfo
				.getJSONArray("CatalogList").getJSONObject(0)
				.getString("CatalogId"));
		productVo.setStock(1);
		OrderVo orderVo = createTestOrderVo(productVo, price);
		// 一个商家一个订单一个商品
		OrderGroupVo groupVo1 = new OrderGroupVo();
		groupVo1.setSellerId(sellerId);
		groupVo1.setSellerLoginId(sellerName);
		groupVo1.setSellerCoupon(null);
		groupVo1.setOrders(Lists.newArrayList(orderVo));
		req.setOrderGroups(Lists.newArrayList(groupVo1));
		// 买手1 订单组
		return req;
	}

	/**
	 * 1个买手,多商品,生成单个订单
	 * 
	 * @param isUserCoupon
	 *            是否使用优惠券（同时使用平台券，商家券）
	 * @return
	 */
	public static TradingServiceResp placeOrder2(boolean isUserCoupon) {

		return placeOrder2(isUserCoupon, false);

	}

	/**
	 * 1个买手,多商品,生成单个订单
	 * 
	 * @param isUserCoupon
	 *            是否使用优惠券（同时使用平台券，商家券）
	 * @param virtualProduct
	 *            是否虚拟商品
	 * @return
	 */
	public static TradingServiceResp placeOrder2(boolean isUserCoupon,
			boolean virtualProduct) {

		PlaceOrderReq placeOrderReq = TradingCallService
				.buildStandPlaceOrderReq(false);

		long userId = placeOrderReq.getUserId();

		// 买手1 订单组
		OrderGroupVo groupVo1 = placeOrderReq.getOrderGroups().get(0);

		TradingCallService.ProductVo productVo1 = null;

		long sellerId = groupVo1.getSellerId();

		String sellerName = groupVo1.getSellerLoginId();

		productVo1 = TradingCallService.creaderPro(sellerId, sellerName, 10);

		OrderItemVo orderItemVo1 = TradingCallService.createOrderItemVo(
				productVo1.getProductId(), productVo1.getCatalogId());

		groupVo1.getOrders().get(0).getOrderItems()
				.addAll(Lists.newArrayList(orderItemVo1));

		if (isUserCoupon) {

			CouponVo sellerCoupon1 = TradingCallService.createSellerCouponVo(
					userId, sellerId, new BigDecimal(30), BigDecimal.TEN);

			groupVo1.setSellerCoupon(sellerCoupon1);

			CouponVo ymatouCoupon = TradingCallService.createYMTCouponVo(
					userId, new BigDecimal(60), BigDecimal.TEN);
			placeOrderReq.setYmatouCoupon(ymatouCoupon);

		}

		// 虚拟商品
		if (virtualProduct)
			placeOrderReq.getOrderGroups().get(0).getOrders().get(0)
					.setLogisticsType(LogisticsTypeEnum.AutoDelivery);

		return TradingCallService.callPlaceOrderService(placeOrderReq);

	}

	/**
	 * 1个买手,多商品,生成2个订单
	 * 
	 * @param isUserCoupon
	 *            是否使用优惠券（同时使用平台券，商家券）
	 * @return
	 */
	public static TradingServiceResp placeOrder3(boolean isUserCoupon) {

		return placeOrder3(isUserCoupon, false);

	}

	/**
	 * 1个买手,多商品,生成2个订单
	 * 
	 * @param isUserCoupon
	 *            是否使用优惠券（同时使用平台券，商家券）
	 * @param logisticsType
	 *            物流方式
	 * @return
	 */
	public static TradingServiceResp placeOrder3(boolean isUserCoupon,
			LogisticsTypeEnum logisticsType) {

		return placeOrder3(isUserCoupon, false, logisticsType);

	}

	/**
	 * 1个买手,多商品,生成2个订单
	 * 
	 * @param isUserCoupon
	 *            是否使用优惠券（同时使用平台券，商家券）
	 * @param canPayDeduct
	 *            是否使用app内立减支付金额
	 * @return
	 */
	public static TradingServiceResp placeOrder3(boolean isUserCoupon,
			boolean canPayDeduct) {

		return placeOrder3(isUserCoupon, canPayDeduct,
				Long.valueOf(EnvSetup.getData("BuyUserId")),
				LogisticsTypeEnum.OVERSEAS_DELIVERY);
	}

	/**
	 * 1个买手,多商品,生成2个订单
	 * 
	 * @param isUserCoupon
	 *            是否使用优惠券（同时使用平台券，商家券）
	 * @param canPayDeduct
	 *            是否使用app内立减支付金额
	 * @param userid
	 * @return
	 */
	public static TradingServiceResp placeOrder3(boolean isUserCoupon,
			boolean canPayDeduct, long userId) {

		return placeOrder3(isUserCoupon, canPayDeduct, userId,
				LogisticsTypeEnum.OVERSEAS_DELIVERY);
	}

	/**
	 * 1个买手,多商品,生成2个订单
	 * 
	 * @param isUserCoupon
	 *            是否使用优惠券（同时使用平台券，商家券）
	 * @param canPayDeduct
	 *            是否使用app内立减支付金额
	 * @param logisticsType
	 *            物流方式
	 * @return
	 */
	public static TradingServiceResp placeOrder3(boolean isUserCoupon,
			boolean canPayDeduct, LogisticsTypeEnum logisticsType) {

		return placeOrder3(isUserCoupon, canPayDeduct,
				Long.valueOf(EnvSetup.getData("BuyUserId")), logisticsType);
	}

	/**
	 * 生成分销订单
	 * 
	 * @param hunterId
	 *            推手id
	 * @param hunterOrderType
	 *            推手订单类型（1：大礼包订单，2：普通订单）
	 * @return
	 * @throws Exception
	 */
	public static TradingServiceResp placeHunterOrder(long hunterId,
			int hunterOrderType) throws Exception {

		return placeHunterOrder(hunterId, 100, 0, hunterOrderType, false, false);
	}

	/**
	 * 生成分销订单
	 * 
	 * @param hunterId
	 *            推手id
	 * @param userId
	 *            用户id
	 * @param hunterOrderType
	 *            推手订单类型（1：大礼包订单，2：普通订单）
	 * @return
	 * @throws Exception
	 */
	public static TradingServiceResp placeHunterOrder(long hunterId,
			long userId, int hunterOrderType) throws Exception {

		return placeHunterOrder(hunterId, 100, userId, hunterOrderType, false, false);
	}
	
	/**
	 * 生成分销订单
	 * 
	 * @param hunterId
	 *            推手id
	 * @param userId
	 *            用户id
	 * @param hunterOrderType
	 *            推手订单类型（1：大礼包订单，2：普通订单） 
	 * @param useCoupon 是否使用优惠券
	 * @return
	 * @throws Exception
	 */
	public static TradingServiceResp placeHunterOrder(long hunterId, int num,
			long userId, int hunterOrderType, boolean userCoupon) throws Exception {

		return placeHunterOrder(hunterId, num, userId, hunterOrderType, userCoupon, false);
	}

	/**
	 * 生成分销订单
	 * 
	 * @param hunterId
	 *            推手id
	 * @param userId
	 *            用户id
	 * @param hunterOrderType
	 *            推手订单类型（1：大礼包订单，2：普通订单）
	 * @param num
	 *            购买数量
	 * @param useCoupon
	 * 		       是否使用优惠券
	 * @return
	 * @throws Exception
	 */
	@Deprecated
	public static TradingServiceResp placeHunterOrder(long hunterId, int num,
			long userId, int hunterOrderType, boolean useCoupon, boolean zeroCommission) throws Exception {

		long sellerId = 20336378;
		String sellerName = "fyftest1";

		PlaceOrderReq placeOrderReq = TradingCallService
				.buildStandPlaceOrderReq(false);
		
//		placeOrderReq.setOrderSource(OrderSourceEnum.C2CWechat);

		OrderGroupVo groupVo = placeOrderReq.getOrderGroups().get(0);

		groupVo.setSellerId(sellerId);
		groupVo.setSellerLoginId(sellerName);
		// placeOrderReq.setUserId(24660246);

		if (userId == 0)
			placeOrderReq
					.setUserId(Long.valueOf(EnvSetup.getData("BuyUserId")));
		else
			placeOrderReq.setUserId(userId);

		placeOrderReq.setHunterId(String.valueOf(hunterId));
		placeOrderReq.setHunterOrderType(String.valueOf(hunterOrderType));
		placeOrderReq.setOrderSource(OrderSourceEnum.HunterMP);
		placeOrderReq.setBizSource(null);

		OrderVo orderVo = groupVo.getOrders().get(0);

		if (hunterOrderType == 1) {
			AddSellerProductRequest addSellerProductBean = ProductManagerCallServiceV2
					.initAddSellerGlobalPspProductRequest((int)sellerId);
			
			String productId = ProductManagerCallServiceV2
					.addNewProduct(addSellerProductBean).get("Data")
					.getAsJsonObject().get("ProductId").getAsString();
			ProductManagerCallServiceV2.AddSellerGlobalPspProduct((int)sellerId, productId, 1);
			List<YmtCatalogsI> catalogslist = new YmtCatalogsIWapper()
					.selectCatalogsByProductId(productId);
			String catalogId = catalogslist.get(0).getsCatalogId();
			OrderItemVo orderItemVo = TradingCallService.createOrderItemVo(
					productId, catalogId);
			
			List<BigDecimal> saleCommissionList = new ArrayList<>();
			
			if (zeroCommission) {
				
				saleCommissionList.add(BigDecimal.ZERO);
				saleCommissionList.add(BigDecimal.ZERO);
				saleCommissionList.add(BigDecimal.ZERO);
				saleCommissionList.add(BigDecimal.ZERO);
			} else {
				
				saleCommissionList.add(new BigDecimal("0.1"));
				saleCommissionList.add(new BigDecimal("0.3"));
				saleCommissionList.add(new BigDecimal("0.5"));
				saleCommissionList.add(new BigDecimal("0.7"));
			}

			ProductManagerCallServiceV2.UpdateCatalogCommisionsV2((int)sellerId,
					productId, catalogId, sellerName, saleCommissionList);
			ProductManagerCallServiceV2.UpdateProductCommision((int)sellerId,
					productId, sellerName, new BigDecimal(0.25));

			orderItemVo.setProductNum(num);
			orderVo.setOrderItems(Lists.newArrayList(orderItemVo));

		} else {
			AddSellerProductRequest addSellerProductBean = ProductManagerCallServiceV2
					.initAddSellerGlobalPspProductRequest((int)sellerId);
			String productId = ProductManagerCallServiceV2
					.addNewProduct(addSellerProductBean).get("Data")
					.getAsJsonObject().get("ProductId").getAsString();
			List<YmtCatalogsI> catalogslist = new YmtCatalogsIWapper()
					.selectCatalogsByProductId(productId);
			String catalogId = catalogslist.get(0).getsCatalogId();
			
//			String productId = "p2204478";
//			String catalogId = "c3849662";
			
			OrderItemVo orderItemVo = TradingCallService.createOrderItemVo(
					productId, catalogId);

			ProductManagerCallServiceV2.UpdateCatalogCommisions((int)sellerId,
					productId, catalogId, sellerName, new BigDecimal("0.6"));
//			ProductManagerCallServiceV2.UpdateCatalogCommisions((int)sellerId,
//					productId, catalogId, sellerName, new BigDecimal("9"));
			ProductManagerCallServiceV2.UpdateProductCommision((int)sellerId,
					productId, sellerName, new BigDecimal(0.25));

//			orderItemVo.setProductPrice(BigDecimal.TEN);
//			orderItemVo.setProductNum(1);
			orderItemVo.setFreight(BigDecimal.ZERO);
			orderVo.setOrderItems(Lists.newArrayList(orderItemVo));
		}
		
		orderVo.setLogisticsType(LogisticsTypeEnum.OVERSEAS_DELIVERY);
		
		if(useCoupon) {
			
			// 使用买手优惠券
			CouponVo sellerCoupon1 = TradingCallService.createSellerCouponVo(
					userId, sellerId, new BigDecimal(30), BigDecimal.TEN);
	
			groupVo.setSellerCoupon(sellerCoupon1);
			
			// 使用平台优惠券
			CouponVo ymatouCoupon = TradingCallService.createYMTCouponVo(userId,
					new BigDecimal(60), BigDecimal.TEN);
			placeOrderReq.setYmatouCoupon(ymatouCoupon);
		}
		
		TradingServiceResp resp = TradingCallService
				.callPlaceOrderService(placeOrderReq);

		return resp;
	}
	
	/**
	 * 生成特殊大礼包分销订单
	 * 
	 * @param hunterId
	 *            推手id
	 * @param userId
	 *            用户id
	 * @param hunterOrderType
	 *            推手订单类型（1：大礼包订单，2：普通订单）
	 * @param num
	 *            购买数量
	 * @param useCoupon
	 * 		       是否使用优惠券
	 * @return
	 * @throws Exception
	 */
	@Deprecated
	public static TradingServiceResp placeSpecialGiftBagHunterOrder(long hunterId, int num,
			long userId, boolean useCoupon, boolean zeroCommission) throws Exception {

		long sellerId = 20336378;
		String sellerName = "fyftest1";
		
		String productId = "p2148963";
		String catalogId = "c3702475";

		PlaceOrderReq placeOrderReq = TradingCallService
				.buildStandPlaceOrderReq(false);

		OrderGroupVo groupVo = placeOrderReq.getOrderGroups().get(0);

		groupVo.setSellerId(sellerId);
		groupVo.setSellerLoginId(sellerName);

		if (userId == 0)
			placeOrderReq
					.setUserId(Long.valueOf(EnvSetup.getData("BuyUserId")));
		else
			placeOrderReq.setUserId(userId);

		placeOrderReq.setHunterId(String.valueOf(hunterId));
		placeOrderReq.setHunterOrderType("1");
		placeOrderReq.setOrderSource(OrderSourceEnum.HunterMP);
		placeOrderReq.setBizSource(null);

		OrderVo orderVo = groupVo.getOrders().get(0);
		
		updateGiftBagProductNum(productId, (int)sellerId, catalogId);
		
		OrderItemVo orderItemVo = TradingCallService.createOrderItemVo(
				productId, catalogId);
		
		List<BigDecimal> saleCommissionList = new ArrayList<>();
		
		if (zeroCommission) {
			
			saleCommissionList.add(BigDecimal.ZERO);
			saleCommissionList.add(BigDecimal.ZERO);
			saleCommissionList.add(BigDecimal.ZERO);
			saleCommissionList.add(BigDecimal.ZERO);
		} else {
			
			saleCommissionList.add(new BigDecimal("0.1"));
			saleCommissionList.add(new BigDecimal("0.3"));
			saleCommissionList.add(new BigDecimal("0.5"));
			saleCommissionList.add(new BigDecimal("0.7"));
		}

		ProductManagerCallServiceV2.UpdateCatalogCommisionsV2((int)sellerId,
				productId, catalogId, sellerName, saleCommissionList);
		ProductManagerCallServiceV2.UpdateProductCommision((int)sellerId,
				productId, sellerName, new BigDecimal(0.25));

		orderItemVo.setProductNum(num);
		orderVo.setOrderItems(Lists.newArrayList(orderItemVo));
		
		orderVo.setLogisticsType(LogisticsTypeEnum.PackageDelivery);
		
		if(useCoupon) {
			
			// 使用买手优惠券
			CouponVo sellerCoupon1 = TradingCallService.createSellerCouponVo(
					userId, sellerId, new BigDecimal(30), BigDecimal.TEN);
	
			groupVo.setSellerCoupon(sellerCoupon1);
			
			// 使用平台优惠券
			CouponVo ymatouCoupon = TradingCallService.createYMTCouponVo(userId,
					new BigDecimal(60), BigDecimal.TEN);
			placeOrderReq.setYmatouCoupon(ymatouCoupon);
		}
		
		TradingServiceResp resp = TradingCallService
				.callPlaceOrderService(placeOrderReq);

		return resp;
	}
	
	/**
	 * 生成优选团商品分销订单
	 * 
	 * @param hunterId
	 *            推手id
	 * @param userId
	 *            用户id
	 * @param num
	 *            购买数量
	 * @return
	 * @throws Exception
	 */
	public static TradingServiceResp placeHunterOptimizedOrder(long hunterId,
			int num, long userId) throws Exception {
		return placeHunterOptimizedOrder(hunterId, num, userId, false, false);
	}
	
	/**
	 * 生成优选团商品分销订单
	 * 
	 * @param hunterId
	 *            推手id
	 * @param userId
	 *            用户id
	 * @param num
	 *            购买数量
	 * @return
	 * @throws Exception
	 */
	public static TradingServiceResp placeHunterOptimizedOrder(long hunterId,
			int num, long userId, boolean mixProduct) throws Exception {
		return placeHunterOptimizedOrder(hunterId, num, userId, mixProduct, false);
	}
	
	/**
	 * 生成优选团商品分销订单
	 * 
	 * @param hunterId
	 *            推手id
	 * @param userId
	 *            用户id
	 * @param num
	 *            购买数量
	 *            
	 * @param mixProduct 是否添加一个普通商品
	 * @param zeroCommission 是否0佣金
	 * @return
	 * @throws Exception
	 */
	@Deprecated
	public static TradingServiceResp placeHunterOptimizedOrder(long hunterId, int num,
			long userId, boolean mixProduct, boolean zeroCommission) throws Exception {

		int sellerId = 20336378;
		String sellerName = "fyftest1";

		PlaceOrderReq placeOrderReq = TradingCallService
				.buildStandPlaceOrderReq(false);

		OrderGroupVo groupVo = placeOrderReq.getOrderGroups().get(0);

		groupVo.setSellerId(sellerId);
		groupVo.setSellerLoginId(sellerName);
		// placeOrderReq.setUserId(24660246);

		if (userId == 0)
			placeOrderReq
					.setUserId(Long.valueOf(EnvSetup.getData("BuyUserId")));
		else
			placeOrderReq.setUserId(userId);

		placeOrderReq.setHunterId(String.valueOf(hunterId));
		placeOrderReq.setHunterOrderType("2");
		placeOrderReq.setOrderSource(OrderSourceEnum.HunterMP);
		placeOrderReq.setBizSource(null);

		OrderVo orderVo = groupVo.getOrders().get(0);

		AddSellerProductRequest addSellerProductBean = ProductManagerCallServiceV2
				.initAddSellerGlobalPspProductRequest(sellerId);

		String productId = ProductManagerCallServiceV2
				.addNewProduct(addSellerProductBean).get("Data")
				.getAsJsonObject().get("ProductId").getAsString();
		ProductManagerCallServiceV2.AddSellerGlobalPspProduct(sellerId,
				productId, 2);
		List<YmtCatalogsI> catalogslist = new YmtCatalogsIWapper()
				.selectCatalogsByProductId(productId);
		String catalogId = catalogslist.get(0).getsCatalogId();
		
//		String productId = "p2205094";
//		String catalogId = "c3850171";
		
		OrderItemVo orderItemVo = TradingCallService.createOrderItemVo(
				productId, catalogId);
		
		ProductManagerCallServiceV2.UpdateCatalogCommisions(sellerId,
				productId, catalogId, sellerName, new BigDecimal("0.6"));
		ProductManagerCallServiceV2.UpdateProductCommision(sellerId,
				productId, sellerName, new BigDecimal(0.25));
		
		//旧版优选团，需要设置saleCommissionList
//		List<BigDecimal> saleCommissionList = new ArrayList<>();
//		
//		if (zeroCommission) {
//			
//			saleCommissionList.add(BigDecimal.ZERO);
//			saleCommissionList.add(BigDecimal.ZERO);
//			saleCommissionList.add(BigDecimal.ZERO);
//			saleCommissionList.add(BigDecimal.ZERO);
//		} else {
//			
//			saleCommissionList.add(new BigDecimal("7.00"));
//			saleCommissionList.add(new BigDecimal("8.00"));
//			saleCommissionList.add(new BigDecimal("9.00"));
//			saleCommissionList.add(new BigDecimal("10.00"));
//		}
//
//		ProductManagerCallServiceV2.UpdateCatalogCommisionsV2(sellerId,
//				productId, catalogId, sellerName, saleCommissionList);
//		ProductManagerCallServiceV2.UpdateProductCommision(sellerId,
//				productId, sellerName, new BigDecimal(0.25));

		orderItemVo.setProductNum(num);
		orderVo.setOrderItems(Lists.newArrayList(orderItemVo));
		
		//如果混合了普通商品，则添加一个普通商品
		if (mixProduct) {
			
			AddSellerProductRequest addSellerProductBean1 = ProductManagerCallServiceV2
					.initAddSellerGlobalPspProductRequest(sellerId);
			String productId1 = ProductManagerCallServiceV2
					.addNewProduct(addSellerProductBean1).get("Data")
					.getAsJsonObject().get("ProductId").getAsString();
			List<YmtCatalogsI> catalogslist1 = new YmtCatalogsIWapper()
					.selectCatalogsByProductId(productId1);
			String catalogId1 = catalogslist1.get(0).getsCatalogId();
			OrderItemVo orderItemVo1 = TradingCallService.createOrderItemVo(
					productId1, catalogId1);

			ProductManagerCallServiceV2.UpdateCatalogCommisions(sellerId,
					productId1, catalogId1, sellerName, new BigDecimal("0.6"));
			ProductManagerCallServiceV2.UpdateProductCommision(sellerId,
					productId1, sellerName, new BigDecimal(0.25));

			orderItemVo1.setProductNum(num);
			orderVo.getOrderItems().add(orderItemVo1);
		}

		orderVo.setLogisticsType(LogisticsTypeEnum.PackageDelivery);

		TradingServiceResp resp = TradingCallService
				.callPlaceOrderService(placeOrderReq);

		return resp;
	}

	/**
	 * 1个买手,多商品,生成2个订单
	 * 
	 * @param isUserCoupon
	 *            是否使用优惠券（同时使用平台券，商家券）
	 * @param canPayDeduct
	 *            是否使用app内立减支付金额
	 * @param userId
	 *            买家用户id
	 * @return
	 */
	public static TradingServiceResp placeOrder3(boolean isUserCoupon,
			boolean canPayDeduct, long userId, LogisticsTypeEnum logisticsType) {

		PlaceOrderReq placeOrderReq = TradingCallService
				.buildStandPlaceOrderReq(false, canPayDeduct, userId);
		
//		placeOrderReq.setRebatePaidAmount(BigDecimal.TEN);
//		
//		placeOrderReq.setDiscount(BigDecimal.TEN);

//		// 买手1 订单组
		OrderGroupVo groupVo1 = placeOrderReq.getOrderGroups().get(0);

		TradingCallService.ProductVo productVo1 = null;
		TradingCallService.ProductVo productVo2 = null;
		TradingCallService.ProductVo productVo3 = null;
//
		long sellerId = groupVo1.getSellerId();
//
		String sellerName = groupVo1.getSellerLoginId();

		productVo1 = TradingCallService.creaderPro(sellerId, sellerName, 10);
		productVo2 = TradingCallService.creaderPro(sellerId, sellerName, 10);
		productVo3 = TradingCallService.creaderPro(sellerId, sellerName, 10);

		OrderItemVo orderItemVo1 = TradingCallService.createOrderItemVo(
				productVo1.getProductId(), productVo1.getCatalogId());
//		OrderItemVo orderItemVo1 = TradingCallService.createOrderItemVo(
//				"p2665276", "c4752394");
		OrderItemVo orderItemVo2 = TradingCallService.createOrderItemVo(
				productVo2.getProductId(), productVo2.getCatalogId());
//
		groupVo1.getOrders().get(0).getOrderItems()
				.addAll(Lists.newArrayList(orderItemVo1, orderItemVo2));
		groupVo1.getOrders().get(0).setLogisticsType(logisticsType);
//		groupVo1.getOrders().get(0).setOrderType(4);

		OrderVo OrderVo1 = TradingCallService.createOrderVo(Lists
				.newArrayList(productVo3));

		groupVo1.getOrders().add(OrderVo1);
		
//		// 定义买手下的优惠商品信息list
//		List<SellerPromotionVo> sellerPromotionList = new ArrayList<SellerPromotionVo>();
//
//		SellerPromotionVo sellerPromotion1 = new SellerPromotionVo();
//
//		sellerPromotion1.setAmountCondition(new BigDecimal(100));
//		sellerPromotion1.setId(123456789);
//		sellerPromotion1.setName("自动化商家优惠活动");
//
//		sellerPromotion1.setPromotionValue(new BigDecimal(12));
//		sellerPromotion1.setQtyCondition(4);
//
//		sellerPromotion1.setReducedAmount(new BigDecimal(15));
//		sellerPromotion1.setType(PromotionTypeEnum.ReduceIfAmountEnough);
//
//		sellerPromotion1.setApportions(Arrays.asList(new CatalogApportionVo(
//				orderItemVo1.getCatalogId(), orderItemVo1.getProductNum()),
//				new CatalogApportionVo(orderItemVo2.getCatalogId(),
//						orderItemVo2.getProductNum())));
//
//		sellerPromotionList.add(sellerPromotion1);
//
//		groupVo1.setSellerPromotionApportions(sellerPromotionList);

		if (isUserCoupon) {

			CouponVo sellerCoupon1 = TradingCallService.createSellerCouponVo(
					userId, sellerId, new BigDecimal(30), BigDecimal.TEN);

			groupVo1.setSellerCoupon(sellerCoupon1);

			CouponVo ymatouCoupon = TradingCallService.createYMTCouponVo(
					userId, new BigDecimal(60), BigDecimal.TEN);
			placeOrderReq.setYmatouCoupon(ymatouCoupon);
		}

		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}

	/**
	 * 多买手,多商品,生成多个订单
	 * 
	 * @param isUserCoupon
	 *            是否使用优惠券（同时使用平台券，商家券）
	 * @return
	 */
	public static TradingServiceResp placeOrder4(boolean isUserCoupon) {

		return placeOrder4(isUserCoupon, false,
				Long.valueOf(EnvSetup.getData("BuyUserId")));

	}

	/**
	 * 多买手,多商品,生成多个订单
	 * 
	 * @param isUserCoupon
	 *            是否使用优惠券（同时使用平台券，商家券）
	 * @param canPayDeduct
	 *            是否使用app内立减支付金额
	 * @return
	 */
	public static TradingServiceResp placeOrder4(boolean isUserCoupon,
			boolean canPayDeduct) {

		return placeOrder4(isUserCoupon, canPayDeduct,
				Long.valueOf(EnvSetup.getData("BuyUserId")));

	}

	/**
	 * 多买手,多商品,生成多个订单
	 * 
	 * @param isUserCoupon
	 *            是否使用优惠券（同时使用平台券，商家券）
	 * @param canPayDeduct
	 *            是否使用app内立减支付金额
	 * @param userId
	 *            买家id
	 * @return
	 */
	public static TradingServiceResp placeOrder4(boolean isUserCoupon,
			boolean canPayDeduct, long userId) {

		PlaceOrderReq placeOrderReq = TradingCallService
				.buildStandPlaceOrderReq(false, canPayDeduct, userId);

		// long userId = placeOrderReq.getUserId();

		// 买手1 订单组
		OrderGroupVo groupVo1 = placeOrderReq.getOrderGroups().get(0);

		TradingCallService.ProductVo productVo1 = null;
		TradingCallService.ProductVo productVo2 = null;
		TradingCallService.ProductVo productVo3 = null;

		long sellerId = groupVo1.getSellerId();
		String sellerName = groupVo1.getSellerLoginId();

		productVo1 = TradingCallService.creaderPro(sellerId, sellerName, 10);
		productVo2 = TradingCallService.creaderPro(sellerId, sellerName, 10);
		productVo3 = TradingCallService.creaderPro(sellerId, sellerName, 10);

		OrderItemVo orderItemVo1 = TradingCallService.createOrderItemVo(
				productVo1.getProductId(), productVo1.getCatalogId());
		OrderItemVo orderItemVo2 = TradingCallService.createOrderItemVo(
				productVo2.getProductId(), productVo2.getCatalogId());

		groupVo1.getOrders().get(0).getOrderItems()
				.addAll(Lists.newArrayList(orderItemVo1, orderItemVo2));

		OrderVo OrderVo1 = TradingCallService.createOrderVo(Lists
				.newArrayList(productVo3));

		groupVo1.getOrders().add(OrderVo1);

		if (isUserCoupon) {

			CouponVo sellerCoupon1 = TradingCallService.createSellerCouponVo(
					userId, sellerId, new BigDecimal(30), BigDecimal.TEN);

			groupVo1.setSellerCoupon(sellerCoupon1);

			CouponVo ymatouCoupon = TradingCallService.createYMTCouponVo(
					userId, new BigDecimal(60), BigDecimal.TEN);
			placeOrderReq.setYmatouCoupon(ymatouCoupon);

		}

		// 买手2 订单组
		long sellerId2 = Long.valueOf(EnvSetup.getData("SellerId"));

		String sellerName2 = String.valueOf(EnvSetup.getData("SellerName"));

		TradingCallService.ProductVo productVo4 = null;
		TradingCallService.ProductVo productVo5 = null;
		TradingCallService.ProductVo productVo6 = null;

		OrderGroupVo groupVo2 = TradingCallService.createOrderGroupVo(
				sellerId2, sellerName2);

		productVo4 = TradingCallService.creaderPro(sellerId2, sellerName2, 10);
		productVo5 = TradingCallService.creaderPro(sellerId2, sellerName2, 10);
		productVo6 = TradingCallService.creaderPro(sellerId2, sellerName2, 10);

		OrderItemVo orderItemVo4 = TradingCallService.createOrderItemVo(
				productVo4.getProductId(), productVo1.getCatalogId());
		OrderItemVo orderItemVo5 = TradingCallService.createOrderItemVo(
				productVo5.getProductId(), productVo2.getCatalogId());

		groupVo2.getOrders().get(0).getOrderItems()
				.addAll(Lists.newArrayList(orderItemVo4, orderItemVo5));

		OrderVo OrderVo2 = TradingCallService.createOrderVo(Lists
				.newArrayList(productVo6));

		groupVo2.getOrders().add(OrderVo2);
		groupVo2.setOrders(Lists.newArrayList(OrderVo2));

		placeOrderReq.getOrderGroups().add(groupVo2);

		if (isUserCoupon) {

			CouponVo sellerCoupon2 = TradingCallService.createSellerCouponVo(
					userId, sellerId2, new BigDecimal(30), BigDecimal.TEN);

			groupVo2.setSellerCoupon(sellerCoupon2);

		}

		return TradingCallService.callPlaceOrderService(placeOrderReq);

	}

	/**
	 * 创建一个定金订单
	 * 
	 * @param usePrecreditCard
	 *            是否使用预付卡
	 */
	public static TradingServiceResp placeEngageOrder(boolean usePrecreditCard) {

		return placeEngageOrder(usePrecreditCard,
				Long.valueOf(EnvSetup.getData("BuyUserId")));
	}

	/**
	 * 创建一个定金订单
	 * 
	 * @param usePrecreditCard
	 *            是否使用预付卡
	 * @param userId
	 *            用户id
	 */
	public static TradingServiceResp placeEngageOrder(boolean usePrecreditCard,
			long userId) {

		PlaceOrderReq placeOrderReq = TradingCallService
				.buildStandPlaceOrderReq(false, false, userId);

		// placeOrderReq.getOrderGroups().get(0).getOrders().get(0)
		// .setEarnestAmount(TestDataManager.randomPrice(BigDecimal.ZERO,
		// BigDecimal.TEN));
		
//		placeOrderReq.setOrderSource(OrderSourceEnum.C2CWechat);
		
		placeOrderReq.getOrderGroups().get(0).getOrders().get(0)
				.getOrderItems().get(0).setEarnestAmount(BigDecimal.ONE);
		placeOrderReq.getOrderGroups().get(0).getOrders().get(0)
				.getOrderItems().get(0)
				.setBookingPromotionAmount(new BigDecimal("20.00"));
		placeOrderReq.getOrderGroups().get(0).getOrders().get(0)
				.setPaymentStartTime(DateTime.now().plusDays(1).toDate());
		placeOrderReq.getOrderGroups().get(0).getOrders().get(0)
				.setPaymentEndTime(DateTime.now().plusDays(2).toDate());

		if (usePrecreditCard) {

			PrepaidCardVo prepaidCardVo = new PrepaidCardVo();

			prepaidCardVo.setCardAmount(BigDecimal.ONE);
			prepaidCardVo.setCardNo(PrepaidCardService.cardId1);

			placeOrderReq.setPrepaidCardVos(Arrays.asList(prepaidCardVo));

		}

		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}

	/**
	 * 单个买手,多商品,生成多个定金订单
	 * 
	 * @param usePrecreditCard
	 *            是否使用预付卡
	 */
	public static TradingServiceResp placeEngageOrder2(boolean usePrecreditCard) {

		return placeEngageOrder2(usePrecreditCard,
				Long.valueOf(EnvSetup.getData("BuyUserId")));
	}

	/**
	 * 单个买手,多商品,生成多个定金订单
	 * 
	 * @param usePrecreditCard
	 *            是否使用预付卡
	 * @param userId
	 *            用户id
	 * @return
	 */
	public static TradingServiceResp placeEngageOrder2(
			boolean usePrecreditCard, long userId) {

		PlaceOrderReq placeOrderReq = TradingCallService
				.buildStandPlaceOrderReq(false, false, userId);

		// 买手第一个订单组
		OrderGroupVo groupVo1 = placeOrderReq.getOrderGroups().get(0);

		Date paymentStartTime = DateTime.now().plusDays(1).toDate();
		Date paymentEndTime = DateTime.now().plusDays(2).toDate();

		OrderItemVo orderItemVo1 = placeOrderReq.getOrderGroups().get(0)
				.getOrders().get(0).getOrderItems().get(0);
		orderItemVo1.setBookingPromotionAmount(BigDecimal.TEN);
		orderItemVo1.setEarnestAmount(BigDecimal.ONE);

		// 第一个订单
		OrderVo orderVo1 = groupVo1.getOrders().get(0);

		orderVo1.setPaymentStartTime(paymentStartTime);
		orderVo1.setPaymentEndTime(paymentEndTime);

		// 第二个订单
		OrderVo orderVo2 = TradingCallService.createOrderVo();
		orderVo2.getOrderItems().get(0)
				.setBookingPromotionAmount(BigDecimal.TEN);
		orderVo2.getOrderItems().get(0).setEarnestAmount(BigDecimal.ONE);

		orderVo2.setPaymentStartTime(paymentStartTime);
		orderVo2.setPaymentEndTime(paymentEndTime);

		groupVo1.getOrders().add(orderVo2);

		if (usePrecreditCard) {

			PrepaidCardVo prepaidCardVo = new PrepaidCardVo();

			prepaidCardVo.setCardAmount(BigDecimal.ONE);
			prepaidCardVo.setCardNo(PrepaidCardService.cardId1);

			placeOrderReq.setPrepaidCardVos(Arrays.asList(prepaidCardVo));

		}
		
		placeOrderReq.setPlaceOrderSource("二次确认");

		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}

	/**
	 * 单个买手,多商品,生成多个定金订单
	 * 
	 * @param usePrecreditCard
	 *            是否使用预付卡
	 * @param userId
	 *            用户id
	 * @return
	 */
	public static PlaceOrderReq buildEngagePlaceOrderReq(
			boolean usePrecreditCard) {

		PlaceOrderReq placeOrderReq = TradingCallService
				.buildStandPlaceOrderReq(false);

		// 买手第一个订单组
		OrderGroupVo groupVo1 = placeOrderReq.getOrderGroups().get(0);

		Date paymentStartTime = DateTime.now().plusDays(1).toDate();
		Date paymentEndTime = DateTime.now().plusDays(2).toDate();

		// 第一个商品
		OrderItemVo orderItemVo1 = placeOrderReq.getOrderGroups().get(0)
				.getOrders().get(0).getOrderItems().get(0);
		orderItemVo1.setBookingPromotionAmount(BigDecimal.TEN);
		orderItemVo1.setEarnestAmount(BigDecimal.ONE);

		// 第二个商品
		ProductVo productVo1 = TradingCallService.creaderPro(24635724L,
				"autotest1", 10);
//		ProductVo productVo1 = TradingCallService.creaderPro(3383L,
//				"autotest1", 10);
		OrderItemVo orderItemVo2 = TradingCallService.createOrderItemVo(
				productVo1.getProductId(), productVo1.getCatalogId());
		orderItemVo2.setBookingPromotionAmount(BigDecimal.TEN);
		orderItemVo2.setEarnestAmount(BigDecimal.ONE);

		// 第一个订单
		OrderVo orderVo1 = groupVo1.getOrders().get(0);

		orderVo1.setPaymentStartTime(paymentStartTime);
		orderVo1.setPaymentEndTime(paymentEndTime);

		orderVo1.setLogisticsType(LogisticsTypeEnum.OVERSEAS_DELIVERY);
		orderVo1.getOrderItems().add(orderItemVo2);

		// 第二个订单
		OrderVo orderVo2 = TradingCallService.createOrderVo();
		orderVo2.getOrderItems().get(0)
				.setBookingPromotionAmount(BigDecimal.TEN);
		orderVo2.getOrderItems().get(0).setEarnestAmount(BigDecimal.ONE);

		orderVo2.setPaymentStartTime(paymentStartTime);
		orderVo2.setPaymentEndTime(paymentEndTime);

		orderVo2.setLogisticsType(LogisticsTypeEnum.OVERSEAS_DELIVERY);

//		groupVo1.getOrders().add(orderVo2);

		if (usePrecreditCard) {

			PrepaidCardVo prepaidCardVo = new PrepaidCardVo();

			prepaidCardVo.setCardAmount(BigDecimal.ONE);
			prepaidCardVo.setCardNo(PrepaidCardService.cardId1);

			placeOrderReq.setPrepaidCardVos(Arrays.asList(prepaidCardVo));

		}

		return placeOrderReq;
	}

	/**
	 * 单个买手,多商品,生成多个定金订单
	 * 
	 * @param usePrecreditCard
	 *            是否使用预付卡
	 * @param sellerId
	 *            买手id
	 * @param sellerName
	 *            买手名称
	 * @return
	 */
	public static PlaceOrderReq buildEngagePlaceOrderReq(
			boolean usePrecreditCard, long sellerId, String sellerName) {

		PlaceOrderReq placeOrderReq = TradingCallService
				.buildStandPlaceOrderReq(false, sellerId, sellerName);

		// 买手第一个订单组
		OrderGroupVo groupVo1 = placeOrderReq.getOrderGroups().get(0);

		Date paymentStartTime = DateTime.now().plusDays(1).toDate();
		Date paymentEndTime = DateTime.now().plusDays(2).toDate();

		OrderItemVo orderItemVo1 = placeOrderReq.getOrderGroups().get(0)
				.getOrders().get(0).getOrderItems().get(0);
		orderItemVo1.setBookingPromotionAmount(BigDecimal.TEN);
		orderItemVo1.setEarnestAmount(BigDecimal.ONE);

		// 第一个订单
		OrderVo orderVo1 = groupVo1.getOrders().get(0);

		orderVo1.setPaymentStartTime(paymentStartTime);
		orderVo1.setPaymentEndTime(paymentEndTime);

		// 第二个订单
		OrderVo orderVo2 = TradingCallService.createOrderVo();
		orderVo2.getOrderItems().get(0)
				.setBookingPromotionAmount(BigDecimal.TEN);
		orderVo2.getOrderItems().get(0).setEarnestAmount(BigDecimal.ONE);

		orderVo2.setPaymentStartTime(paymentStartTime);
		orderVo2.setPaymentEndTime(paymentEndTime);

		groupVo1.getOrders().add(orderVo2);

		if (usePrecreditCard) {

			PrepaidCardVo prepaidCardVo = new PrepaidCardVo();

			prepaidCardVo.setCardAmount(BigDecimal.ONE);
			prepaidCardVo.setCardNo(PrepaidCardService.cardId1);

			placeOrderReq.setPrepaidCardVos(Arrays.asList(prepaidCardVo));

		}

		return placeOrderReq;
	}

	/**
	 * @param userId
	 *            用户id
	 * @param earnestAmount
	 *            定金金额
	 * @param tradingId
	 *            交易号
	 */
	public static Long payEngageOrder(long userId, BigDecimal earnestAmount,
			long tradingId) {

		// 支付定金
		return TradingCallService.payOrder(userId, earnestAmount, tradingId, 2);
	}

	/**
	 * 二次确认下单
	 * 
	 * @param userId
	 *            用户id
	 * @param orderId
	 *            订单id
	 */
	public static TradingServiceResp placeFullPaidOrder(long userId,
			long orderId) {

		List<Long> bookingConfirmOrderIds = new ArrayList<Long>();
		bookingConfirmOrderIds.add(orderId);

		return TradingCallService.placeOrder(bookingConfirmOrderIds);
	}

	/**
	 * 定金订单二次确认下单，使用商家+平台优惠，使用预付卡，使用商家促销信息
	 * 
	 * @param placeOrderResp
	 */
	public static TradingServiceResp placeFullPaidOrder2(
			TradingServiceResp placeOrderResp) {

		OrderShardingWapper orderShardingWapper = new OrderShardingWapper();
		PlaceOrderReq placeOrderReq = new PlaceOrderReq();

		Long userId = placeOrderResp.getUserId();
		long tradingId = placeOrderResp.getTradingId();
		List<com.ymatou.iapi.optrade.resp.Order> orderList = placeOrderResp
				.getOrderList();

		List<OrderDetailPo> orderDetailList = new ArrayList<OrderDetailPo>();

		// 支付定金
		TradingCallService.payOrder(userId, placeOrderResp.getPayableAmount(),
				tradingId, 2);
		List<Long> bookingConfirmOrderIds = new ArrayList<Long>();

		for (com.ymatou.iapi.optrade.resp.Order order : orderList) {

			bookingConfirmOrderIds.add(order.getOrderId());

			OrderDetailPo po = orderShardingWapper.selectOrderDetailbyOrderId(
					order.getOrderId()).get(0);
			orderDetailList.add(po);
		}

		placeOrderReq.setAddressId(772208L);
		placeOrderReq.setUserId(userId);
		placeOrderReq.setMainOrderId(TradingCallService
				.genMainOrderId(placeOrderReq.getUserId()));

		OrderGroupVo groupVo1 = new OrderGroupVo();
		groupVo1.setSellerId(Long.valueOf(EnvSetup.getData("autotest_seller1")));
		groupVo1.setSellerLoginId(String.valueOf(EnvSetup
				.getData("autotest_sellerName1")));
		groupVo1.setBookingConfirmOrderIds(bookingConfirmOrderIds);

		// 使用买手优惠券
		long sellerId = groupVo1.getSellerId();

		CouponVo sellerCoupon1 = TradingCallService.createSellerCouponVo(
				userId, sellerId, new BigDecimal(30), BigDecimal.TEN);

		groupVo1.setSellerCoupon(sellerCoupon1);

		// 定义买手营销信息list
		List<SellerPromotionVo> sellerPromotionList = new ArrayList<SellerPromotionVo>();

		SellerPromotionVo sellerPromotion1 = new SellerPromotionVo();

		sellerPromotion1.setAmountCondition(new BigDecimal(50));
		sellerPromotion1.setId(123456789);
		sellerPromotion1.setName("自动化商家优惠活动");

		sellerPromotion1.setPromotionValue(new BigDecimal(12));
		sellerPromotion1.setQtyCondition(4);

		sellerPromotion1.setReducedAmount(new BigDecimal(15));
		sellerPromotion1.setType(PromotionTypeEnum.ReduceIfAmountEnough);

		sellerPromotion1.setApportions(Arrays.asList(new CatalogApportionVo(
				orderDetailList.get(0).getCatalogId(), orderDetailList.get(0)
						.getProductCount()), new CatalogApportionVo(
				orderDetailList.get(1).getCatalogId(), orderDetailList.get(1)
						.getProductCount())));

		sellerPromotionList.add(sellerPromotion1);

		groupVo1.setSellerPromotionApportions(sellerPromotionList);

		// 使用平台优惠券
		CouponVo ymatouCoupon = TradingCallService.createYMTCouponVo(userId,
				new BigDecimal(60), BigDecimal.TEN);
		placeOrderReq.setYmatouCoupon(ymatouCoupon);

		placeOrderReq.setOrderGroups(Lists.newArrayList(groupVo1));
		placeOrderReq.setAppId("ymt autotest");
		placeOrderReq.setPlaceOrderSource("二次确认订单");

		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}

	/**
	 * 定金订单二次确认下单
	 * 
	 * @param orderList
	 */
	public static TradingServiceResp placeFullPaidOrder2(
			List<com.ymatou.iapi.optrade.resp.Order> orderList) {

		List<Long> bookingConfirmOrderIds = new ArrayList<Long>();

		for (com.ymatou.iapi.optrade.resp.Order order : orderList) {

			bookingConfirmOrderIds.add(order.getOrderId());
		}

		PlaceOrderReq placeOrderReq = new PlaceOrderReq();

		placeOrderReq.setAddressId(772208L);
		placeOrderReq.setUserId(orderList.get(0).getOrderPo().getUserId());
		placeOrderReq.setMainOrderId(TradingCallService
				.genMainOrderId(placeOrderReq.getUserId()));
		OrderGroupVo groupVo1 = new OrderGroupVo();

		groupVo1.setSellerId(Long.valueOf(EnvSetup.getData("autotest_seller1")));
		groupVo1.setSellerLoginId(String.valueOf(EnvSetup
				.getData("autotest_sellerName1")));

		groupVo1.setBookingConfirmOrderIds(bookingConfirmOrderIds);
		placeOrderReq.setOrderGroups(Lists.newArrayList(groupVo1));
		placeOrderReq.setAppId("ymt autotest");

		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}

	/**
	 * 二次确认并支付
	 * 
	 * @param userId
	 *            用户id
	 * @param orderId
	 *            订单id
	 */
	public static Long payFullPaidOrder(long userId, long orderId) {

		List<Long> bookingConfirmOrderIds = new ArrayList<Long>();
		bookingConfirmOrderIds.add(orderId);

		TradingServiceResp fullPaidResp = TradingCallService
				.placeOrder(bookingConfirmOrderIds);
		BigDecimal useAccountAmount = fullPaidResp.getPayableAmount();
		long fullPaidTradingId = fullPaidResp.getTradingId();

		// 二次确认并支付
		return TradingCallService.payOrder(userId, useAccountAmount,
				fullPaidTradingId, 1);
	}

	/**
	 * 取消订单
	 * 
	 * @param orderId
	 * @param type
	 * @param userId
	 */
	public static void cancelOrder(long orderId, CancelOrderTypeEnum type,
			long userId) {

		CancelOrderReq cancelorderReq = new CancelOrderReq();
		CancelOrderCall cancelordercall = new CancelOrderCall();

		cancelorderReq.setCancelReason("自动化测试取消订单");
		cancelorderReq.setCancelType(type);
		cancelorderReq.setOrderId(orderId);
		cancelorderReq.setUserId(userId);

		cancelordercall.setData(false, cancelorderReq);
		try {

			cancelordercall.callService();

		} catch (Exception e) {
			Logger.info(String.format("########取消订单:%s 异常", orderId));
		}
	}

	/**
	 * 支付前取消订单
	 * 
	 * @param CancelOrderTypeEnum
	 *            type
	 * @return
	 */
	public static TradingServiceResp cancelOrderBeforePaid(
			CancelOrderTypeEnum buyercancelorder) {

		TradingServiceResp placeOrderResp = placeOrder1(false, false);

		long userId = placeOrderResp.getUserId();

		OrderPo orderPo = placeOrderResp.getOrderList().get(0).getOrderPo();

		long orderId = orderPo.getOrderId();

		long sellerId = orderPo.getSellerId();

		long operateId;

		switch (buyercancelorder.getCode()) {
		case 1:
			operateId = userId;
			break;
		case 2:
			operateId = sellerId;
			break;
		case 4:
			operateId = -1;
			break;
		default:
			operateId = -1;
			break;

		}

		cancelOrder(orderId, buyercancelorder, operateId);

		return placeOrderResp;

	}

	/**
	 * 支付后取消订单
	 * 
	 * @param CancelOrderTypeEnum
	 *            type
	 * @return
	 */
	public static TradingServiceResp cancelOrderAfterPaid() {

		TradingServiceResp placeOrderResp = payOrder();

		OrderPo orderPo = placeOrderResp.getOrderList().get(0).getOrderPo();

		long orderId = orderPo.getOrderId();
		long userId = placeOrderResp.getUserId();

		cancelOrder(orderId, CancelOrderTypeEnum.BUYER_CANCEL_ORDER, userId);

		return placeOrderResp;

	}

	/**
	 * 创建一个用余额支付成的订单
	 * 
	 * @return
	 */
	public static TradingServiceResp payOrder() {

		TradingServiceResp placeOrderResp = placeOrder1(false, false);
		
//		PlaceOrderReq placeOrderReq = TradingCallService.buildStandPlaceOrderReq(false,
//				false, 25008362, 25326671, "wesper");
//		
//		OrderItemVo orderItem = placeOrderReq.getOrderGroups().get(0)
//				.getOrders().get(0).getOrderItems().get(0);
//		
//		orderItem.setProductId("p2629283");
//		orderItem.setCatalogId("c4683426");
//		
//		orderItem.setProductNum(1);
////		orderItem.setProductPrice(new BigDecimal("0.01"));
//		orderItem.setFreight(BigDecimal.ZERO);
//		
//		TradingServiceResp placeOrderResp = TradingCallService.callPlaceOrderService(placeOrderReq);
		
		try {
			String acc = AccountCallServiceV2.getAccountId(Long.valueOf(
					placeOrderResp.getUserId()).intValue());
			AccountCallServiceV2.resetAccount(acc, new BigDecimal("10000"),
					new BigDecimal("0"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		payOrder(placeOrderResp.getUserId(), placeOrderResp.getPayableAmount(),
				placeOrderResp.getMainOrderId(), "13");

		return placeOrderResp;

	}
	
	/**
	 * 创建一个用余额支付成的订单
	 * @userId
	 * @return
	 */
	public static TradingServiceResp payOrder(int userId) {

		TradingServiceResp placeOrderResp = placeOrder(userId);
		try {
			String acc = AccountCallServiceV2.getAccountId(Long.valueOf(
					placeOrderResp.getUserId()).intValue());
			AccountCallServiceV2.resetAccount(acc, new BigDecimal("10000"),
					new BigDecimal("0"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		payOrder(placeOrderResp.getUserId(), placeOrderResp.getPayableAmount(),
				placeOrderResp.getMainOrderId(), "13");

		return placeOrderResp;

	}

	/**
	 * 创建一个买手已接单的订单
	 * 
	 * @return
	 */
	public static TradingServiceResp orderAccept() {

		TradingServiceResp placeOrderResp = payOrder();

		OrderPo orderPo = placeOrderResp.getOrderList().get(0).getOrderPo();

		long orderId = orderPo.getOrderId();

		// TODO 老交易下线后 去掉
		TradingSyncService.riskControlNotify(orderId, "pass");

		sellerAcceptOrder(orderPo.getSellerId(), orderId);

		return placeOrderResp;

	}

	/**
	 * 订单付款（预付款）时，应付的现金金额
	 * 
	 * @param traingid
	 * @return
	 */
	public static BigDecimal getPayableAmount(long traingid) {

		List<OrderPo> res = new OrderShardingWapper()
				.selectOrderbyMainOrderId(traingid);

		BigDecimal total = BigDecimal.ZERO;
		for (OrderPo orderPo : res) {
			total = total.add(getPayableAmount(orderPo));
		}

		return total;
	}

	/**
	 * 订单付款（预付款）时，应付的现金金额
	 * 
	 * @param orderId
	 * @return
	 */
	private static BigDecimal getPayableAmount(OrderPo orderPo) {

		return orderPo
				.getTotalPrice()
				.add(orderPo.getFreight())
				.add(orderPo.getOrderDiscount())
				.subtract(
						orderPo.getYmtCouponAmount().add(
								orderPo.getSellerCouponAmount()))
				.subtract(orderPo.getPromotionAmount())
				.subtract(orderPo.getYmtPromotionAmount());
	}

	/**
	 * 支付订单
	 * 
	 * @param userId
	 * @param useAccountAmount
	 * @param tradingId
	 */
	public static Long payOrder(long userId, BigDecimal useAccountAmount,
			long tradingId) {

		return payOrder(userId, useAccountAmount, tradingId, false, 1);
	}

	/**
	 * 支付订单
	 * 
	 * @param userId
	 * @param useAccountAmount
	 * @param tradingId
	 * @param payType
	 */
	public static Long payOrder(long userId, BigDecimal useAccountAmount,
			long tradingId, int tradeType) {

		return payOrder(userId, useAccountAmount, tradingId, false, tradeType);
	}

	/**
	 * 支付订单
	 * 
	 * @param userId
	 * @param useAccountAmount
	 * @param tradingId
	 * @param canPayDeductAmount
	 */
	public static Long payOrder(long userId, BigDecimal useAccountAmount,
			long tradingId, boolean canPayDeductAmount) {

		return payOrder(userId, useAccountAmount, tradingId,
				canPayDeductAmount, 1);
	}

	/**
	 * 支付订单
	 * 
	 * @param userId
	 * @param useAccountAmount
	 * @param tradingId
	 * @param thirdPartyDiscountAmount
	 */
	public static Long payOrder(long userId, BigDecimal useAccountAmount,
			long tradingId, BigDecimal totalPrice,
			BigDecimal thirdPartyDiscountAmount) {

		return payOrder(userId, useAccountAmount, tradingId, false, totalPrice,
				thirdPartyDiscountAmount);
	}

	/**
	 * 支付订单
	 * 
	 * @param userId
	 * @param useAccountAmount
	 * @param tradingId
	 * @param canPayDeductAmount
	 * @param thirdPartyDiscountAmount
	 * @throws Exception
	 */
	public static Long payOrder(Long userId, BigDecimal useAccountAmount,
			long tradingId, boolean canPayDeductAmount, BigDecimal totalPrice,
			BigDecimal thirdPartyDiscountAmount) {

		PayReq payReq = new PayReq();

		PayReqCall payReqCall = new PayReqCall();

		long thirdTradingId = 0;

		// 参数
		payReq.setUserId(userId);
		payReq.setCallbackUrl("www.ymatou.com");
		payReq.setUseAccountAmount(useAccountAmount);
		payReq.setTradingId(tradingId);
		String tradingPassword = "abc123";
		payReq.setTradingPwd(tradingPassword);
		payReq.setUserIp("127.0.0.10");

		payReq.setTerminalSource(TerminalSourceEnum.IOS);

		payReq.setPayType("15");
		payReq.setCanPayDeduct(canPayDeductAmount);

		payReqCall.setData(false, payReq);

		try {

			Logger.comment(String.format("用户  %s , 订单支付,交易号 %s, 付款账户余额 : %s ",
					userId, tradingId, useAccountAmount));

			payReqCall.callService();

			thirdTradingId = payReqCall.getData().getLong("tradingId");

		} catch (Exception e) {
			Logger.info(String.format("########支付订单 交易号:%s 异常", tradingId));
		}

		// 支付网关支付回调交易
		try {
			PayGateWayCallService.notifyCall("15",
					String.valueOf(thirdTradingId),
					totalPrice.subtract(useAccountAmount).toString(),
					userId.intValue(), thirdPartyDiscountAmount);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return thirdTradingId;
	}

	/**
	 * 支付订单
	 * 
	 * @param userId
	 * @param useAccountAmount
	 * @param tradingId
	 * @param canPayDeductAmount
	 */
	public static Long payOrder(long userId, BigDecimal useAccountAmount,
			long tradingId, boolean canPayDeductAmount, int tradeType) {

		PayReq payReq = new PayReq();

		PayReqCall payReqCall = new PayReqCall();

		long thirdTradingId = 0;

		// 参数
		payReq.setUserId(userId);
		payReq.setCallbackUrl("www.ymatou.com");
		payReq.setUseAccountAmount(useAccountAmount);
		payReq.setTradingId(tradingId);
		String tradingPassword = userId == 30164301 ? "Abc123456" : "abc123";
//		String tradingPassword = "123456";
		payReq.setTradingPwd(tradingPassword);
		payReq.setUserIp("127.0.0.10");
		payReq.setTradeType(tradeType);

		payReq.setTerminalSource(TerminalSourceEnum.IOS);

		payReq.setPayType("13");
		payReq.setCanPayDeduct(canPayDeductAmount);

		payReqCall.setData(false, payReq);

		try {

			Logger.comment(String.format("用户  %s , 订单支付,交易号 %s, 付款账户余额 : %s ",
					userId, tradingId, useAccountAmount));

			payReqCall.callService();

			thirdTradingId = payReqCall.getData().getLong("tradingId");

			if (payReqCall.getData().optString("errorMessage")
					.equalsIgnoreCase("账户金额不足")) {

				String accountid1 = AccountCallServiceV2
						.getAccountId((int) userId);
				AccountCallServiceV2.resetAccount(accountid1, new BigDecimal(
						9000000), new BigDecimal(0));

				payOrder(userId, useAccountAmount, tradingId,
						canPayDeductAmount, tradeType);
			}
		} catch (Exception e) {
			Logger.info(e.toString());
			Logger.info(String.format("########支付订单 交易号:%s 异常", tradingId));
		}

		return thirdTradingId;
	}

	public static Long payOrder(long userId, BigDecimal useAccountAmount,
			long tradingId, String payType) {
		return payOrder(userId, useAccountAmount, tradingId, payType, 1);
	}

	/**
	 * 支付订单
	 * 
	 * @param userId
	 * @param useAccountAmount
	 * @param tradingId
	 * @param payType
	 */
	public static Long payOrder(long userId, BigDecimal useAccountAmount,
			long tradingId, String payType, int tradeType) {

		PayReq payReq = new PayReq();

		PayReqCall payReqCall = new PayReqCall();

		long thirdTradingId = 0;

		// 参数
		payReq.setUserId(userId);
		payReq.setCallbackUrl("www.ymatou.com");
		payReq.setUseAccountAmount(useAccountAmount);
		payReq.setTradingId(tradingId);
		String tradingPassword = "abc123";
		payReq.setTradingPwd(tradingPassword);
		payReq.setUserIp("127.0.0.10");
		payReq.setBankId("");
		payReq.setTradeType(tradeType);

		payReq.setTerminalSource(TerminalSourceEnum.IOS);

		if (payType.equals("70")) {

			payType = "13";

			// 转宝付 70 支付渠道
			payReq.setOptionalPayTypes(Arrays.asList(70));
		}

		payReq.setPayType(payType);
		payReqCall.setData(false, payReq);

		try {

			Logger.comment(String.format("用户  %s , 订单支付,交易号 %s, 付款账户余额 : %s ",
					userId, tradingId, useAccountAmount));

			if (useAccountAmount.compareTo(BigDecimal.ZERO) == 0) {

				String accountid1;
				try {
					accountid1 = AccountCallServiceV2
							.getAccountId((int) userId);
					AccountCallServiceV2.resetAccount(accountid1,
							new BigDecimal(9000000), new BigDecimal(0));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			payReqCall.callService();

			thirdTradingId = payReqCall.getData().getLong("tradingId");

			// TODO 老交易下线后 去掉
			Thread.sleep(2000);

		} catch (Exception e) {
			Logger.info(String.format("########支付订单 交易号:%s 异常", tradingId));
		}

		return thirdTradingId;
	}

	/**
	 * 商家接单
	 * 
	 * @param sellerId
	 * @param orderId
	 */
	public static void sellerAcceptOrder(long sellerId, long orderId) {

		// TODO 老交易下线后 去掉
		TradingSyncService.riskControlNotify(orderId, "pass");

		AcceptOrderReq acceptorderbean = new AcceptOrderReq();

		SellerAcceptOrderCall acceptordercall = new SellerAcceptOrderCall();

		// 接单
		acceptorderbean.setOrderId(orderId);
		acceptorderbean.setSellerId(sellerId);
		acceptorderbean.setCsId(1234);
		
		// 发送请求
		acceptordercall.setData(false, acceptorderbean);
		try {

			Logger.comment(String.format("orderId %s, sellerId %s 接单 , ",
					orderId, sellerId));

			acceptordercall.callService();
		} catch (Exception e) {
			Logger.info(String.format("########商家接单  订单号:%s 异常", orderId));
		}

	}

	/**
	 * 创建一个申请退款中的订单
	 * 
	 * @return
	 */
	public static TradingServiceResp orderApplyRefund() {
		TradingServiceResp resp = orderAccept();

		RefundService.applyRefund(resp.getOrderList().get(0));

		return resp;
	}

	/**
	 * 创建一个 已发货订单
	 * 
	 * @return
	 */
	public static TradingServiceResp orderDelivery() {
		TradingServiceResp resp = orderAccept();

		Order order = resp.getOrderList().get(0);

		long sellerId = order.getSellerId();
		long orderId = order.getOrderId();

		delivery(sellerId, orderId, true);

		return resp;
	}

	/**
	 * 码头保存发货物流单号
	 * 
	 * @param orderId
	 * @param sellerId
	 * @param billCode
	 */
	public static void saveDeliverSummary(long orderId, long sellerId,
			String billCode) {

		try {
			YmatouEasyCall SaveDeliverSummaryCall = new YmatouEasyCall("",
					"POST", "JSON");
			StringBuffer saveDeliverSummaryString = new StringBuffer();
			saveDeliverSummaryString
					.append("{\"SaveDeliverSummaryInfos\":[{\"BillCode\":\"");
			saveDeliverSummaryString.append(billCode);
			saveDeliverSummaryString.append("\",");
			saveDeliverSummaryString
					.append("\"CanReDelivery\":0,\"CatalogStatus\":\"7\",\"DeliverType\":2,\"ExpressCode\":\"xlobo\",\"InnerExpressCode\":\"\",\"IsChinaDeliver\":true,");
			saveDeliverSummaryString.append("\"OrderId\":");
			saveDeliverSummaryString.append(orderId);
			saveDeliverSummaryString.append(",");
			saveDeliverSummaryString
					.append("\"Provider\":\"洋码头官方合作物流（xLobo贝海国际速递）\",");
			saveDeliverSummaryString.append("\"SellerId\":");
			saveDeliverSummaryString.append(sellerId);
			saveDeliverSummaryString.append(",");
			saveDeliverSummaryString.append("\"Weight\":10}]}");
			SaveDeliverSummaryCall
			// .setUrl("http://orderdelivery.iapi.ymatou.com/api/Deliver/SaveDeliverSummary");
					.setUrl("http://api.seller.ymatou.com/api/Deliver/SaveDeliverSummary");

			SaveDeliverSummaryCall.setData(saveDeliverSummaryString.toString());

			Logger.comment("发货保存运单号");
			SaveDeliverSummaryCall.callService();

		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	/**
	 * 订单发货
	 * 
	 * @param sellerId
	 * @param orderId
	 * @param isShippedByXlobo
	 * @return 物流单号
	 */
	public static String delivery(Long sellerId, long orderId,
			boolean isShippedByXlobo) {

		DeliverGoodsReq deliveryReq = new DeliverGoodsReq();
		DeliverGoodsCall deliveryCall = new DeliverGoodsCall();

		// 物流单号
		String DeliverSummary = TestDataManager.randomStr(13);

		DeliveryInfo deliveryInfo = new DeliveryInfo();

		deliveryInfo.setBillNo(DeliverSummary);
		deliveryInfo.setYmtExpressCode("Y013");
		deliveryInfo.setExpressName("ems");
		deliveryInfo.setDeliverySection(3);
		deliveryInfo.setDeliverySource(1);
		deliveryInfo.setOrderId(orderId);

		deliveryReq.setSellerId(sellerId);
		deliveryReq.setDeliveryInfos(Arrays.asList(deliveryInfo));

		deliveryCall.setData(false, deliveryReq);
		
		try {
			deliveryCall.callService();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return DeliverSummary;
	}

	/**
	 * 订单发货
	 * 
	 * @param sellerId
	 * @param orderId
	 * @param LogisticsType
	 *            :Unknown(0),China(1),US(2),SailProtect(3),BondedDelivery(4),
	 *            XloboBondedDelivery
	 *            (5),AuthenticatedDirectDelivery(6),PackageDelivery
	 *            (7),AutoDelivery(8)
	 * @param section
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static String delivery(Long sellerId, long orderId,
			LogisticsTypeEnum logisticsType, int section)
			throws ClientProtocolException, IOException {

		DeliverGoodsReq deliveryReq = new DeliverGoodsReq();
		DeliverGoodsCall deliveryCall = new DeliverGoodsCall();
		DeliveryInfo dInfo = new DeliveryInfo();
		String billNo = TestDataManager.getRandomNum(13);

		deliveryReq.setSellerId(sellerId);

		dInfo.setDeliverySection(section);
		dInfo.setDeliverySource(1);
		dInfo.setExpressName("sf");
		dInfo.setBillNo(billNo);
		dInfo.setYmtExpressCode("Y013");
		dInfo.setOrderId(orderId);

		deliveryReq.setDeliveryInfos(Lists.newArrayList(dInfo));

		deliveryCall.setData(deliveryReq);
		deliveryCall.callService();

		return billNo;
	}

	/**
	 * 订单发货
	 * 
	 * @param sellerId
	 * @param orderId
	 * @param LogisticsType
	 *            :Unknown(0),China(1),US(2),SailProtect(3),BondedDelivery(4),
	 *            XloboBondedDelivery
	 *            (5),AuthenticatedDirectDelivery(6),PackageDelivery
	 *            (7),AutoDelivery(8)
	 * @param section
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static String delivery(Long sellerId, long orderId,
			LogisticsTypeEnum logisticsType, String ymtExpressCode, int section)
			throws ClientProtocolException, IOException {

		return delivery(sellerId, orderId, logisticsType, ymtExpressCode, section, null);
	}
	
	/**
	 * 
	 * @param sellerId
	 * @param orderId
	 * @param logisticsType
	 * @param ymtExpressCode
	 * @param section
	 * @param authenticatePackage
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String delivery(Long sellerId, long orderId,
			LogisticsTypeEnum logisticsType, String ymtExpressCode, int section, Boolean authenticatePackage)
			throws ClientProtocolException, IOException {

		DeliverGoodsReq deliveryReq = new DeliverGoodsReq();
		DeliverGoodsCall deliveryCall = new DeliverGoodsCall();
		DeliveryInfo dInfo = new DeliveryInfo();
		String billNo = "";

		if (ymtExpressCode.equalsIgnoreCase("Y073")
				|| ymtExpressCode.equalsIgnoreCase("Y047")
				|| ymtExpressCode.equalsIgnoreCase("Y136")) {

			billNo = TestDataManager.getRandomNum(12);
			dInfo.setMobile("13612345678");
		} else if (ymtExpressCode.equalsIgnoreCase("Y068")) {
			billNo = "DB2533011979US";
		} else {

			billNo = TestDataManager.getRandomNum(13);
		}

		dInfo.setBillNo(billNo);

		// 发货节点、1国际段,2转运段,3国内段
		dInfo.setDeliverySection(section);
		dInfo.setDeliverySource(1);
		dInfo.setExpressName("sf");
		dInfo.setYmtExpressCode(ymtExpressCode);
		dInfo.setOrderId(orderId);
		dInfo.setAuthenticatePackage(authenticatePackage);
		
		deliveryReq.setDeliveryInfos(Lists.newArrayList(dInfo));
		deliveryReq.setSellerId(sellerId);

		deliveryCall.setData(deliveryReq);
		deliveryCall.callService();

		return billNo;
	}
	
	/**
	 * 鉴定中心发货
	 * @param sellerId
	 * @param orderId
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String authenticateDelivery(Long sellerId, long orderId)
			throws ClientProtocolException, IOException {

		AuthenticateDeliveryReq authenticateDeliveryReq = new AuthenticateDeliveryReq();
		AuthenticateDeliveryCall authenticateDeliveryCall = new AuthenticateDeliveryCall();

		String billNo = TestDataManager.getRandomNum(13);

		authenticateDeliveryReq.setSellerId(sellerId);
		authenticateDeliveryReq.setOrderId(orderId);
		authenticateDeliveryReq.setBillNo(billNo);
		authenticateDeliveryReq.setExpressCompany("鉴定中心发货");
		authenticateDeliveryReq.setYmtExpressCode("Y013");

		authenticateDeliveryCall.setData(authenticateDeliveryReq);
		authenticateDeliveryCall.callService();

		return billNo;
	}

	/**
	 * 创建一个确认收货订单
	 * 
	 * @return
	 */
	public static TradingServiceResp orderConfirmReceive() {
		TradingServiceResp resp = orderDelivery();

		long orderId = resp.getOrderList().get(0).getOrderId();

		confirmReceive(resp.getUserId(), orderId);

		return resp;
	}

	/**
	 * 订单确认收货
	 * 
	 * @param userId
	 * @param orderId
	 */
	public static void confirmReceive(long userId, long orderId) {

		ConfirmReceiveReq confirmReceiveReq = new ConfirmReceiveReq();
		ConfirmReceiveCall confirmreceivecall = new ConfirmReceiveCall();

		// 确认收货请求
		confirmReceiveReq.setBuyerId(userId);
		confirmReceiveReq.setOrderId(orderId);
		confirmReceiveReq.setRemark("收到了啊");
		confirmReceiveReq.setIgnoreXloboSignedCheck(true);
		// 发送请求
		confirmreceivecall.setData(false, confirmReceiveReq);
		try {
			confirmreceivecall.callService();
		} catch (Exception e) {

			e.printStackTrace();
		}

	}

	/**
	 * 锁定，解锁订单
	 * 
	 * @param orderId
	 * @param islock
	 *            1 锁定 , 非1 解锁
	 */
	public static void markOrderLock(long orderId, int islock) {

		MarkOrderLockReq markOrderLockReq = new MarkOrderLockReq();
		MarkOrderLockCall markOrderLockCall = new MarkOrderLockCall();

		// 参数
		markOrderLockReq.setOrderId(orderId);
		markOrderLockReq.setLockStatus(islock);

		// 发送请求
		markOrderLockCall.setData(false, markOrderLockReq);

		try {
			markOrderLockCall.callService();
		} catch (Exception e) {

			e.printStackTrace();
		}
	}

	/**
	 * 生成结算
	 * 
	 * @param orderId
	 * @param buyerId
	 * @param sellerId
	 * @param totalPrice
	 */
	public static void generateInvoicesOnOrderReceived(long orderId,
			long buyerId, BigDecimal totalPrice, long sellerId) {

		try {

			for (int i = 0; i < 5; i++) {

				Thread.sleep(i * 1000 + 5000);

				YmatouEasyCall generateInvoicesCall = new YmatouEasyCall("",
						"POST", "JSON");
				StringBuffer generateInvoicesString = new StringBuffer();
				generateInvoicesString.append("{\"BuyerId\":");
				generateInvoicesString.append(buyerId);
				generateInvoicesString.append(",");
				generateInvoicesString
						.append("\"appId\":\"optrade.iapi.ymatou.com\",\"BusinessType\":4,\"ParamExt\":{\"IsShippedByXlobo\":\"false\",");
				generateInvoicesString.append("\"TotalPrice\":");
				generateInvoicesString.append(totalPrice);
				generateInvoicesString.append(",");
				generateInvoicesString.append("\"BizCode\":\"100102\"},");
				generateInvoicesString.append("\"OrderId\":");
				generateInvoicesString.append(orderId);
				generateInvoicesString.append(",");

				generateInvoicesString.append("\"SellerId\":");
				generateInvoicesString.append(sellerId);
				generateInvoicesString.append("}");
				generateInvoicesCall
						.setUrl("http://settlement.iapi.ymatou.com/api/generateInvoicesOnOrderReceived");

				generateInvoicesCall.setData(generateInvoicesString.toString());

				Logger.comment("生成结算");
				generateInvoicesCall.callService();

				if ("ok".equalsIgnoreCase(generateInvoicesCall.getReturnData()))
					break;
			}
		} catch (Exception e) {
			// TODO: handle exception
		}

	}
	
	/**
	 * 获取买手的保密协议签约状态
	 * 
	 * @param sellerId
	 */
	public static boolean checkSignedBAOMI(long sellerId) {

		try {
			YmatouEasyCall checkSignedBAOMICall = new YmatouEasyCall("",
					"POST", "JSON");
			StringBuffer checkSignedBAOMIString = new StringBuffer();
			checkSignedBAOMIString
					.append("{\"sellerIDs\":[");
			checkSignedBAOMIString.append(sellerId);
			checkSignedBAOMIString.append("]}");
			
			checkSignedBAOMICall
					.setUrl("http://sellerquery.iapi.ymatou.com/api/CheckSignedBAOMI");

			checkSignedBAOMICall.setData(checkSignedBAOMIString.toString());

			Logger.comment("获取买手的保密协议签约状态");
			checkSignedBAOMICall.callService();
			
			return new JSONObject(checkSignedBAOMICall.getReturnData()).optJSONObject("Data").optJSONObject("Protocols").optBoolean(String.valueOf(sellerId));

		} catch (Exception e) {
			// TODO: handle exception
			return false;
		}
	}
	
	/**
	 * 检查买手是否在拼邮溯源白名单中(true-在，false-不在)
	 * 
	 * @param sellerId
	 */
	public static boolean checkSwitchBySellerId(long sellerId) {

		try {
			YmatouEasyCall checkSwitchBySellerIdCall = new YmatouEasyCall("",
					"POST", "JSON");
			StringBuffer checkSwitchBySellerIdCallString = new StringBuffer();
			checkSwitchBySellerIdCallString
					.append("{\"SellerId\":");
			checkSwitchBySellerIdCallString.append(sellerId);
			checkSwitchBySellerIdCallString.append(", \"SpecialBusinessNo\":\"pysy0001\"}");
			
			checkSwitchBySellerIdCall
					.setUrl("http://sellerAllocation.iapi.ymatou.com/api/SpecialService/CheckSwitch");

			checkSwitchBySellerIdCall.setData(checkSwitchBySellerIdCallString.toString());

			Logger.comment("检查买手是否在拼邮溯源白名单中");
			checkSwitchBySellerIdCall.callService();
			
			return new JSONObject(checkSwitchBySellerIdCall.getReturnData()).optJSONObject("Data").optBoolean("IsEnable");

		} catch (Exception e) {
			// TODO: handle exception
			return false;
		}
	}
	
	@SuppressWarnings("deprecation")
	public static void updateGiftBagProductNum(String productId, int sellerId, String catalogId) {
		
		UpdateProductCatalogsBean updateProductCatalogsBean = new UpdateProductCatalogsBean();
		UpdateProductCatalogsCall updateProductCatalogsCall = new UpdateProductCatalogsCall();
		
		updateProductCatalogsBean.setProductID(productId);
		updateProductCatalogsBean.setUserID(sellerId);
		UpdateProductCatalogDto updateCatalogDto = new UpdateProductCatalogDto();
		updateCatalogDto.setCatalogId(catalogId);
		updateCatalogDto.setUserId(sellerId);
		updateCatalogDto.setNum(1000000);
		updateCatalogDto.setPrice(Double.valueOf("16.00"));
		updateCatalogDto.setVipPrice(Double.valueOf("12.00"));
		updateCatalogDto.setNewCustomerPrice(Double.valueOf("8.00"));
		updateCatalogDto.setMarketPrice(Double.valueOf("20.00"));
		updateProductCatalogsBean.setCatalogs(Arrays.asList(updateCatalogDto));
		
		JSONObject ret = updateProductCatalogsCall.callAndGetReturnData(updateProductCatalogsBean);
		
		try {
			
			if (ret.getInt("Code") == 200)
				Logger.comment("修改库存成功");
			else
				Logger.comment("修改库存失败");
		} catch(JSONException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 商品支付金额（不包含运费）
	 * @param orderDetailPo
	 * @return
	 */
	public static BigDecimal getOrderDetailPaidAmountExcludeFreight(
			OrderDetailPo orderDetailPo) {
		return Utils
				.zeroIfNull(orderDetailPo.getProductPrice())
				.multiply(new BigDecimal(orderDetailPo.getProductCount()))
				.add(Utils.zeroIfNull(orderDetailPo.getDiscount()))
				.subtract(Utils.zeroIfNull(orderDetailPo.getYmtCouponAmount()))
				.subtract(
						Utils.zeroIfNull(orderDetailPo.getSellerCouponAmount()))
				.subtract(Utils.zeroIfNull(orderDetailPo.getPromotionAmount()))
				.subtract(
						Utils.zeroIfNull(orderDetailPo.getYmtPromotionAmount()))
				.subtract(Utils.zeroIfNull(orderDetailPo.getRebatePaidAmount()));
	}
	
	/**
	 * 商品支付金额
	 * @param orderDetailPo
	 * @return
	 */
	public static BigDecimal getOrderDetailPaidAmount(
			OrderDetailPo orderDetailPo) {
		return Utils
				.zeroIfNull(orderDetailPo.getProductPrice())
				.multiply(new BigDecimal(orderDetailPo.getProductCount()))
				.add(Utils.zeroIfNull(orderDetailPo.getDiscount()))
				.subtract(Utils.zeroIfNull(orderDetailPo.getYmtCouponAmount()))
				.subtract(
						Utils.zeroIfNull(orderDetailPo.getSellerCouponAmount()))
				.subtract(Utils.zeroIfNull(orderDetailPo.getPromotionAmount()))
				.subtract(
						Utils.zeroIfNull(orderDetailPo.getYmtPromotionAmount()))
				.subtract(Utils.zeroIfNull(orderDetailPo.getRebatePaidAmount()))
				.add(Utils.zeroIfNull(orderDetailPo.getFreight()));
	}
	
	public static Boolean isCanceledOrder(OrderPo orderPo) {
		
		if (orderPo.getOrderStatus() == 13 || orderPo.getOrderStatus() == 12 || orderPo.getOrderStatus() == 18)
			return true;
		else
			return false;
	}
	
	public static String queryByTradingId(String paymentId) throws Exception {
		
		QueryByTradingIdBean queryByTradingIdBean = new QueryByTradingIdBean();
		QueryByTradingIdCall queryByTradingIdCall = new QueryByTradingIdCall();
		
		queryByTradingIdBean.setTradingId(paymentId);
		
		queryByTradingIdCall.setData(queryByTradingIdBean);
		
		queryByTradingIdCall.callService();
		
		JSONObject object = new JSONObject(queryByTradingIdCall.getReturnData()).getJSONObject("Result");
		
		return String.valueOf(object.getDouble("OrderAmt"));
	}
	
	/**
	 * 保存已签收的物流信息
	 * @param billCode
	 */
	public static void saveLogisticsInfo(String billCode) {

		try {
			YmatouEasyCall saveLogisticsInfoCall = new YmatouEasyCall("",
					"POST", "JSON");
			StringBuffer saveLogisticsInfoString = new StringBuffer();

			saveLogisticsInfoString
					.append("{\"bizContent\":\"{\\\"cpCode\\\":\\\"ZTO\\\", ");
			saveLogisticsInfoString
					.append("\\\"mailNo\\\":\\\"" + billCode + "\\\",");
			saveLogisticsInfoString
					.append("\\\"logisticsGmtModified\\\":\\\"2020-06-17 17:03:24\\\",");
			saveLogisticsInfoString.append("\\\"bizKey\\\":\\\"" + billCode
					+ "\\\",");
			saveLogisticsInfoString
					.append("\\\"logisticsStatusDesc\\\":\\\"已签收\\\",");
			saveLogisticsInfoString
					.append("\\\"lastLogisticDetail\\\":\\\"[代收点]您的快件已签收，签收人在【丰巢的新华.天玺大厦(丰巢智能快递柜)】(新华.天玺大厦D座员工通道)领取,如有疑问请电联：4000633333, 投诉电话：13644023631, 您的快递已经妥投。风里来雨里去, 只为客官您满意。上有老下有小, 赏个好评好不好？【请在评价快递员处帮忙点亮五颗星星哦~】\\\",");
			saveLogisticsInfoString
					.append("\\\"logisticsStatus\\\":\\\"SIGN\\\"}\",");
			saveLogisticsInfoString
					.append("\"billNo\": \"" + billCode + "\", ");
			saveLogisticsInfoString.append("\"platform\":4}");

			saveLogisticsInfoCall
					.setUrl("http://recvlogistics.iapi.ymatou.com/Express/SaveLogisticsInfo");
			saveLogisticsInfoCall.setData(saveLogisticsInfoString.toString());

			Logger.comment("保存已签收的物流信息");
			saveLogisticsInfoCall.callService();

		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	public static void syncSignedOrderBizParam(Long orderId, String billCode)
			throws ClientProtocolException, IOException {

		SyncSignedOrderReq syncSignedOrderReq = new SyncSignedOrderReq();
		SyncSignedOrderCall syncSignedOrderCall = new SyncSignedOrderCall();

		SyncSignedOrderBizParamVo bizParam = new SyncSignedOrderBizParamVo();

		bizParam.setOrderId(orderId);
		bizParam.setBillCode(billCode);
		bizParam.setNodeStatus(5);

		syncSignedOrderReq.setAppId("autotest");
		syncSignedOrderReq.setBizkey(String.valueOf(orderId));
		syncSignedOrderReq.setBizParam(bizParam);
		syncSignedOrderReq.setBizType("LogisticsNotify");

		syncSignedOrderCall.setData(syncSignedOrderReq);
		syncSignedOrderCall.callService();
	}
	
	/**
	 * 
	 * @param authenticateFreightType
	 * @param authenticateFreight
	 * @param authenticateFeeType
	 * @param AuthenticateFee
	 * @return
	 */
	public static TradingServiceResp placeOrderWithAuthenticate(
			AuthenticateFreightTypeEnum authenticateFreightType,
			BigDecimal authenticateFreight,
			AuthenticateFeeTypeEnum authenticateFeeType,
			BigDecimal authenticateFee) {

		PlaceOrderReq placeOrderReq = TradingCallService
				.buildStandPlaceOrderReq(false);

		OrderVo orderVo = placeOrderReq.getOrderGroups().get(0).getOrders()
				.get(0);
		OrderItemVo orderItemVo = orderVo.getOrderItems().get(0);

		orderVo.setAuthenticateFreight(authenticateFreight);
		orderVo.setAuthenticateFreightType(authenticateFreightType.getCode());

		orderItemVo.setAuthenticateFlag(true);
		orderItemVo.setAuthenticateFee(authenticateFee);
		orderItemVo.setAuthenticateFeeType(authenticateFeeType.getCode());
		orderItemVo.setProductNum(orderItemVo.getProductNum() + 1);

		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}
	
	/**
	 * 
	 * @param authenticateFreightType
	 * @param authenticateFreight
	 * @param authenticateFeeTypeEnum
	 * @param AuthenticateFee
	 * @return
	 */
	public static TradingServiceResp placeOrderWithAuthenticateWithTwoProduct(
			AuthenticateFreightTypeEnum authenticateFreightType,
			BigDecimal authenticateFreight,
			AuthenticateFeeTypeEnum authenticateFeeType,
			BigDecimal authenticateFee) {

		PlaceOrderReq placeOrderReq = TradingCallService
				.buildStandPlaceOrderReq(false);

		OrderVo orderVo = placeOrderReq.getOrderGroups().get(0).getOrders()
				.get(0);
		OrderItemVo orderItemVo = orderVo.getOrderItems().get(0);

		orderVo.setAuthenticateFreight(authenticateFreight);
		orderVo.setAuthenticateFreightType(authenticateFreightType.getCode());

		orderItemVo.setAuthenticateFlag(true);
		orderItemVo.setAuthenticateFee(authenticateFee);
		orderItemVo.setAuthenticateFeeType(authenticateFeeType.getCode());
		orderItemVo.setProductNum(orderItemVo.getProductNum() + 1);
		
		TradingCallService.ProductVo pro = TradingCallService.creaderPro(
				placeOrderReq.getOrderGroups().get(0).getSellerId(), "sellerName", 100);

		OrderItemVo orderItemVo_order1_2 = TradingCallService
				.createOrderItemVo(pro.getProductId(), pro.getCatalogId());

		orderItemVo_order1_2.setAuthenticateFlag(true);
		orderItemVo_order1_2.setAuthenticateFee(authenticateFee);
		orderItemVo_order1_2.setAuthenticateFeeType(authenticateFeeType.getCode());
		
		orderVo.getOrderItems().add(orderItemVo_order1_2);

		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}
	
	/**
	 * 买家鉴定费商品、买手鉴定费商品、普通商品一起下单
	 */
	public static TradingServiceResp placeOrderWithAuthenticateWithThreeTypeProduct() {

		PlaceOrderReq placeOrderReq = TradingCallService
				.buildStandPlaceOrderReq(false);

		OrderVo orderVo = placeOrderReq.getOrderGroups().get(0).getOrders()
				.get(0);
		OrderItemVo orderItemVo = orderVo.getOrderItems().get(0);

		// 买手鉴定运费
		orderVo.setAuthenticateFreight(BigDecimal.ONE);
		orderVo.setAuthenticateFreightType(AuthenticateFreightTypeEnum.SELLER.getCode());

		// 买手鉴定费商品
		orderItemVo.setAuthenticateFlag(true);
		orderItemVo.setAuthenticateFee(BigDecimal.TEN);
		orderItemVo.setAuthenticateFeeType(AuthenticateFeeTypeEnum.SELLER.getCode());
		orderItemVo.setProductNum(orderItemVo.getProductNum() + 1);

		// 买家鉴定费商品
		TradingCallService.ProductVo pro = TradingCallService.creaderPro(
				placeOrderReq.getOrderGroups().get(0).getSellerId(),
				"sellerName", 100);

		OrderItemVo orderItemVo_order1_2 = TradingCallService
				.createOrderItemVo(pro.getProductId(), pro.getCatalogId());

		orderItemVo_order1_2.setAuthenticateFlag(true);
		orderItemVo.setAuthenticateFee(BigDecimal.TEN);
		orderItemVo.setAuthenticateFeeType(AuthenticateFreightTypeEnum.BUYER.getCode());
		
		// 普通商品
		pro = TradingCallService.creaderPro(
				placeOrderReq.getOrderGroups().get(0).getSellerId(),
				"sellerName", 100);
		
		OrderItemVo orderItemVo_order1_3 = TradingCallService
				.createOrderItemVo(pro.getProductId(), pro.getCatalogId());

		orderVo.getOrderItems().add(orderItemVo_order1_2);
		orderVo.getOrderItems().add(orderItemVo_order1_3);
		
//		placeOrderReq.setYmatouCoupon(TradingCallService.createYMTCouponVo(
//				placeOrderReq.getUserId(), BigDecimal.TEN, BigDecimal.ONE));
//		// 商家券
//		CouponVo sellerCoupon1 = TradingCallService.createSellerCouponVo(
//				placeOrderReq.getUserId(), placeOrderReq.getOrderGroups()
//						.get(0).getSellerId(), new BigDecimal(30),
//				BigDecimal.TEN);
//
//		placeOrderReq.getOrderGroups().get(0).setSellerCoupon(sellerCoupon1);

		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}
	
	/**
	 * 鉴定费和普通商品一起下单
	 */
	public static TradingServiceResp placeOrderWithAuthenticateWithTwoTypeProduct(
			AuthenticateFreightTypeEnum authenticateFreightType,
			BigDecimal authenticateFreight,
			AuthenticateFeeTypeEnum authenticateFeeType,
			BigDecimal authenticateFee) {

		PlaceOrderReq placeOrderReq = TradingCallService
				.buildStandPlaceOrderReq(false);

		OrderVo orderVo = placeOrderReq.getOrderGroups().get(0).getOrders()
				.get(0);
		OrderItemVo orderItemVo = orderVo.getOrderItems().get(0);

		// 鉴定费商品
		orderVo.setAuthenticateFreight(authenticateFreight);
		orderVo.setAuthenticateFreightType(authenticateFreightType
				.getCode());

		orderItemVo.setAuthenticateFlag(true);
		orderItemVo.setAuthenticateFee(authenticateFee);
		orderItemVo.setAuthenticateFeeType(authenticateFeeType
				.getCode());
		orderItemVo.setProductNum(orderItemVo.getProductNum() + 1);

		// 普通商品
		TradingCallService.ProductVo pro = TradingCallService.creaderPro(
				placeOrderReq.getOrderGroups().get(0).getSellerId(),
				"sellerName", 100);

		OrderItemVo orderItemVo_order1_2 = TradingCallService
				.createOrderItemVo(pro.getProductId(), pro.getCatalogId());

		orderVo.getOrderItems().add(orderItemVo_order1_2);

		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}
	
	/**
	 * 
	 * @param authenticateFreightType
	 * @param authenticateFreight
	 * @param authenticateFeeTypeEnum
	 * @param AuthenticateFee
	 * @return
	 */
	public static TradingServiceResp placeOrderWithAuthenticateAndOfficialLogistics(
			AuthenticateFreightTypeEnum authenticateFreightType,
			BigDecimal authenticateFreight,
			AuthenticateFeeTypeEnum authenticateFeeType,
			BigDecimal authenticateFee) {

		PlaceOrderReq placeOrderReq = TradingCallService
				.buildStandPlaceOrderReq(false);

		OrderVo orderVo = placeOrderReq.getOrderGroups().get(0).getOrders()
				.get(0);
		OrderItemVo orderItemVo = orderVo.getOrderItems().get(0);

		orderVo.setAuthenticateFreight(authenticateFreight);
		orderVo.setAuthenticateFreightType(authenticateFreightType.getCode());

		orderItemVo.setAuthenticateFlag(true);
		orderItemVo.setAuthenticateFee(authenticateFee);
		orderItemVo.setAuthenticateFeeType(authenticateFeeType.getCode());
		orderItemVo.setProductNum(orderItemVo.getProductNum() + 1);
		
		orderVo.setOfficialLogistics(true);
		orderVo.setLogisticsAging(15);

		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}
	
	public static TradingServiceResp placeOrderWithAuthenticateAndLogisticsType(
			AuthenticateFreightTypeEnum authenticateFreightType,
			BigDecimal authenticateFreight,
			AuthenticateFeeTypeEnum authenticateFeeType,
			BigDecimal authenticateFee, LogisticsTypeEnum logisticsType) {

		PlaceOrderReq placeOrderReq = TradingCallService
				.buildStandPlaceOrderReq(false);

		OrderVo orderVo = placeOrderReq.getOrderGroups().get(0).getOrders()
				.get(0);
		OrderItemVo orderItemVo = orderVo.getOrderItems().get(0);

		orderVo.setAuthenticateFreight(authenticateFreight);
		orderVo.setAuthenticateFreightType(authenticateFreightType.getCode());

		orderItemVo.setAuthenticateFlag(true);
		orderItemVo.setAuthenticateFee(authenticateFee);
		orderItemVo.setAuthenticateFeeType(authenticateFeeType.getCode());
		orderItemVo.setProductNum(orderItemVo.getProductNum() + 1);
		
		orderVo.setLogisticsType(logisticsType);

		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}
	
	public static void authenticateCenterNotify(Long orderId, String catalogId)
			throws ClientProtocolException, IOException {

		AuthenticateCenterNotifyReq authenticateCenterNotifyReq = new AuthenticateCenterNotifyReq();
		AuthenticateCenterNotifyCall authenticateCenterNotifyCall = new AuthenticateCenterNotifyCall();

		List<IdentifyProdArrivedVo> prodArriveds = new ArrayList<>();
		
		IdentifyProdArrivedVo identifyProdArrivedVo = new IdentifyProdArrivedVo();
		
		identifyProdArrivedVo.setCatalogId(catalogId);
		identifyProdArrivedVo.setLogisticNo("autotest_billNo");
		identifyProdArrivedVo.setArrivedNumber(1);
		
		prodArriveds.add(identifyProdArrivedVo);
		
		authenticateCenterNotifyReq.setProdArriveds(prodArriveds);
		authenticateCenterNotifyReq.setOrderId(orderId);

		authenticateCenterNotifyCall.setData(authenticateCenterNotifyReq);
		authenticateCenterNotifyCall.callService();
	}
	
	/**
	 * 修改/补录运单号
	 * 
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static String modifyOrSupplementBillNo(long orderId, long sellerId,
			String ymtExpressCode, Integer section)
			throws ClientProtocolException, IOException {

		ModifyOrSupplementBillNoReq modifyOrSupplementBillNoReq = new ModifyOrSupplementBillNoReq();
		ModifyOrSupplementBillNoCall modifyOrSupplementBillNoCall = new ModifyOrSupplementBillNoCall();

		ModifyOrSupplementBillNoInfo dInfo = new ModifyOrSupplementBillNoInfo();

		dInfo.setBillNo(TestDataManager.getRandomNum(13));
		dInfo.setSource(13);

		// 发货节点、1国际段,2转运段,3国内段
		dInfo.setDeliverySection(section);
		dInfo.setYmtExpressCode(ymtExpressCode);

		modifyOrSupplementBillNoReq
				.setBillNoInfoList(Lists.newArrayList(dInfo));
		modifyOrSupplementBillNoReq.setOrderId(orderId);
		modifyOrSupplementBillNoReq.setSellerId(sellerId);

		modifyOrSupplementBillNoCall.setData(modifyOrSupplementBillNoReq);
		modifyOrSupplementBillNoCall.callService();
		
		return dInfo.getBillNo();
	}
	
	/**
	 * 修改/补录运单号
	 * 
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static String modifyOrSupplementBillNo(long orderId, long sellerId,
			String ymtExpressCode, Integer section, Boolean authenticatePackage)
			throws ClientProtocolException, IOException {

		ModifyOrSupplementBillNoReq modifyOrSupplementBillNoReq = new ModifyOrSupplementBillNoReq();
		ModifyOrSupplementBillNoCall modifyOrSupplementBillNoCall = new ModifyOrSupplementBillNoCall();

		ModifyOrSupplementBillNoInfo dInfo = new ModifyOrSupplementBillNoInfo();

		dInfo.setBillNo(TestDataManager.getRandomNum(13));
		dInfo.setSource(13);

		// 发货节点、1国际段,2转运段,3国内段
		dInfo.setDeliverySection(section);
		dInfo.setYmtExpressCode(ymtExpressCode);
		dInfo.setAuthenticatePackage(authenticatePackage);

		modifyOrSupplementBillNoReq
				.setBillNoInfoList(Lists.newArrayList(dInfo));
		modifyOrSupplementBillNoReq.setOrderId(orderId);
		modifyOrSupplementBillNoReq.setSellerId(sellerId);

		modifyOrSupplementBillNoCall.setData(modifyOrSupplementBillNoReq);
		modifyOrSupplementBillNoCall.callService();
		
		return dInfo.getBillNo();
	}

	public static void main(String... args) throws Exception {

		System.out.println(TradingCallService.queryByTradingId("13801998699"));
		/*
		 * AddSellerProductRequest addSellerProductBean =
		 * ProductManagerCallServiceV2
		 * .initAddSellerGlobalPspProductRequest(20336378);
		 * 
		 * String productId = ProductManagerCallServiceV2
		 * .addNewProduct(addSellerProductBean).get("Data")
		 * .getAsJsonObject().get("ProductId").getAsString(); List<YmtCatalogsI>
		 * catalogslist = new YmtCatalogsIWapper()
		 * .selectCatalogsByProductId(productId);
		 * 
		 * ProductManagerCallServiceV2.AddSellerGlobalPspProduct(20336378,
		 * productId);
		 * ProductManagerCallServiceV2.UpdateProductCommision(20336378,
		 * productId, "fyftest1", new BigDecimal(0.15));
		 * System.out.println(productId);
		 */
		/*
		 * TradingServiceResp resp = TradingCallService.placeOrder1(true,
		 * false);
		 * 
		 * int orderId = (int) resp.getOrderList().get(0).getOrderId(); int
		 * userId = (int) resp.getUserId();
		 * 
		 * orderCallService.orderPayRequest((int) resp.getUserId(),
		 * resp.getPayableAmount(), resp.getMainOrderId());
		 */

		// creaderPro(24635724L, "autotest1", 1000000);

		// orderCallService.cancelOrder(orderId, userId);
		// TradingCallService.placeHunterOrder(1234, 2);
		// PlaceOrderReq req =
		// TradingCallService.buildStandPlaceOrderReq(false);
		//
		// long sellerId = 20227567;
		//
		// String sellerName = "zhangyi_seller0002";
		//
		// req.getOrderGroups().get(0).setSellerId(sellerId);
		// req.getOrderGroups().get(0).setSellerLoginId(sellerName);
		//
		// OrderVo orderVo;
		//
		// //创建一个普通商品
		// TradingCallService.ProductVo pro = TradingCallService.creaderPro(
		// sellerId, sellerName, 100);
		//
		// orderVo = TradingCallService.createOrderVo(Lists.newArrayList(pro));
		//
		// orderVo.setLogisticsType(LogisticsTypeEnum.BondedDelivery);
		//
		// req.getOrderGroups().get(0).setOrders(Lists.newArrayList(orderVo));
		//
		// req.setBizSource(null);
		//
		// TradingCallService.callPlaceOrderService(req);
		//
		// TradingCallService.cancelOrder(1330014891,
		// CancelOrderTypeEnum.BUYER_CANCEL_ORDER, 20324891);

		// TradingCallService.getProductInfo("p3530445", 0);
//		TradingCallService.generateInvoicesOnOrderReceived(5201218699L,
//				20238699, new BigDecimal("76.00"), 24635724);
		
//		TradingCallService.placeHunterGroupOrder(1234, 1, 20238699);
//		System.out.println(TradingCallService.checkSwitchBySellerId(24635724));
		
//		Logger.comment(AccountCallServiceV2.getAccountBalance((int)25324461, 5).toPlainString());
		/*
		 * ProductManagerCallServiceV2.UpdateCatalogCommisions(20336378,
		 * "0eabd6fa-7d63-410e-8617-9eb3b2bc0cef",
		 * "acd74a21-b2e5-4049-89c1-65e3b92b6135", "fyftest1", new
		 * BigDecimal(9));
		 */

		// TradingCallService.payOrder(20238699, BigDecimal.valueOf(386),
		// 2074828699, false);
		// PlaceOrderService.payOrder(userId, type)
		// TradingCallService.creaderPro(Long.parseLong("24635724"),
		// "autotest1", 1);
		// TradingCallService.orderConfirmReceive();
		// TradingCallService.sellerAcceptOrder(20227567, 1120856434);;
		// resp.getOrderList();
	}
}
